How to Edit Response Data from @wire In LWC

  • Post author:
  • Post category:LWC

✅ Syntax Pattern:

@wire(adapterFunction, { params })
wiredMethod({ data, error }) {
    if (data) {
        // Modify or format the data here
    } else if (error) {
        // Handle the error
    }
}

🧩 Example 1: Edit Standard Object Data (e.g., Contact)

📌 Use Case: You want to capitalize the first name before displaying it.

import { LightningElement, wire } from 'lwc';
import getContact from '@salesforce/apex/ContactController.getContact';

export default class EditWireDataExample extends LightningElement {
    contactName = '';

    @wire(getContact, { contactId: '003XXXXXXXXXXXX' })
    wiredContact({ data, error }) {
        if (data) {
            // Modify response
            this.contactName = data.FirstName.toUpperCase() + ' ' + data.LastName;
        } else if (error) {
            console.error('Error:', error);
        }
    }
}

🧩 Example 2: Modify List Returned by Apex

Let’s say your Apex method returns a list of posts, and you want to format the title before displaying.

🔹 Apex

@AuraEnabled(cacheable=true)
public static List<Post__c> getPosts() {
    return [SELECT Id, Title__c FROM Post__c LIMIT 5];
}

🔹 JavaScript

import { LightningElement, wire } from 'lwc';
import getPosts from '@salesforce/apex/PostController.getPosts';

export default class PostList extends LightningElement {
    posts = [];

    @wire(getPosts)
    wiredPosts({ data, error }) {
        if (data) {
            // Modify titles before assigning
            this.posts = data.map(post => ({
                ...post,
                Title__c: post.Title__c.toUpperCase()  // e.g., capitalize title
            }));
        } else if (error) {
            console.error('Error:', error);
        }
    }
}

🧠 Best Practices

  • Never modify the original data object directly — clone or map it to a new variable before modifying.
  • For complex processing, consider moving transformation logic to a separate utility function.
  • Use the cacheable=true annotation for @AuraEnabled methods to allow reactive @wire usage.