Understanding the Difference Between @wire Properties and @wire Functions in LWC
When working with Lightning Web Components (LWC), the @wire decorator is used to read data reactively. However, there's often confusion between using it with properties versus functions.
Let’s simplify and clarify the distinction.
@wire with a Property — Simplicity and Reactivity
What it means:
Using @wire with a property is like telling Salesforce:
"Fetch the data and assign it automatically. I don't want to manage the logic."
Key Features:
You get a reactive object with .data and .error keys.
Salesforce manages the invocation based on reactive parameters.
Best for simple data display with minimal logic.
Syntax:
js
@wire(fetchContacts) contacts;
Usage in Template:
html
<template if:true={contacts.data}>
<template for:each={contacts.data} for:item="contact">
<p key={contact.Id}>{contact.Name}</p>
</template>
</template>
Ideal When:
You just need to render data as-is.
You don't need complex logic or transformation.
Error handling isn’t critical or is handled elsewhere.
@wire with a Function — Control and Customization
What it means:
Using @wire with a function tells Salesforce:
"Give me the data, and I’ll decide what to do with it."
Key Features:
You receive data and error as arguments.
You control how to handle and manipulate the response.
Great for custom processing, filtering, or dynamic UI logic.
Syntax:
js
@wire(fetchContacts)
handleContacts({ data, error }) {
if (data) {
// Example: Only include contacts with email addresses
this.filteredContacts = data.filter(c => c.Email);
} else if (error) {
this.showErrorNotification(error);
}
}
Ideal When:
You need to filter, sort, or transform data.
Error handling must vary based on context.
You need conditional assignments or advanced logic.
Real-World Example Comparison:
Scenario: You want to display a list of contacts — only those with a phone number.
Using a Wire Property (not ideal here):
js
@wire(fetchContacts) contacts;
In the template, you’d have to manually check each one not efficient.
Using a Wire Function (better control):
js
@wire(fetchContacts)
processContacts({ data, error }) {
if (data) {
this.contactsWithPhone = data.filter(c => c.Phone);
} else if (error) {
this.notifyUser(error.message);
}
}
Pro Tip:
Use @wire property when your component just needs to show data without much logic.
Use @wire function when you need custom behavior, data transformation, or enhanced error handling.
No comments:
Post a Comment