Sub topic 1
Recap: the wire service and reactive parameters
This chapter reviews how the LWC wire service works, so the later chapters on the graphql wire adapter build on a solid base. It is the first of 13 chapters. It covers only the wire service and reactive parameters. GraphQL syntax and the uiapi schema come later.
Prerequisites
This chapter assumes you already have the following:
- Basic Lightning web component structure: a JavaScript class that extends
LightningElement, and an HTML template in the same folder. - Familiarity with Salesforce objects, fields, and relationships.
- A rough idea of what a GraphQL query looks like. You do not need to write one yet.
You should be able to deploy a component to a scratch org or sandbox and add it to a Lightning page, or run it in a local development setup.
What the wire service does
The wire service is the part of Lightning Web Components that connects a component to a data source. You declare what you want, and the platform provisions the data and delivers it to your component. You do not call a server method yourself.
A wire has three parts:
- An adapter. It is a function imported from a module such as
lightning/uiRecordApior, in this tutorial,lightning/uiGraphQLApi. The adapter knows how to fetch one kind of data. - Configuration. It is an object of parameters passed to the adapter, such as a record ID or a query.
- A target. It is either a property or a function in your class. The platform assigns or calls it with the result.
The platform calls the adapter when the component is connected to the page and again whenever a reactive parameter changes. Results are cached on the client, so several components that ask for the same data can share one response.
Two ways to receive data
The wire target can be a property or a function. The choice affects how you handle results.
Wiring to a property
With a property target, the platform assigns an object with data and error keys. The property starts as undefined, and your template or getters must tolerate that.
import { LightningElement, wire } from 'lwc';
import { getRecord } from 'lightning/uiRecordApi';
import NAME_FIELD from '@salesforce/schema/Account.Name';
export default class AccountName extends LightningElement {
recordId = '001000000000001AAA';
@wire(getRecord, { recordId: '$recordId', fields: [NAME_FIELD] })
account;
get name() {
return this.account?.data?.fields.Name.value;
}
}The optional chaining operator (?.) guards against the property being undefined before the first response arrives.
Wiring to a function
With a function target, the platform calls the function each time a new result is available. The function receives one argument, an object with the same keys. You can destructure it.
import { LightningElement, wire } from 'lwc';
import { getRecord } from 'lightning/uiRecordApi';
import NAME_FIELD from '@salesforce/schema/Account.Name';
export default class AccountNameFn extends LightningElement {
recordId = '001000000000001AAA';
name;
failed = false;
@wire(getRecord, { recordId: '$recordId', fields: [NAME_FIELD] })
handleRecord({ data, error }) {
if (data) {
this.name = data.fields.Name.value;
this.failed = false;
} else if (error) {
this.name = undefined;
this.failed = true;
}
}
}A function target lets you reshape data before it reaches the template. The first chapter example for the GraphQL adapter uses this form to map edges into plain objects. Be aware that the function can run more than once, so it must be safe to repeat and must not assume it runs only on first load.
The following table compares the two forms.
| Aspect | Property target | Function target |
|---|---|---|
| Initial state | `undefined` until the first result | Function not called until a result exists |
| Reshaping data | Use a getter | Do it in the function |
| Keeping the full result object | Yes, the property holds it | No, you receive a copy of the keys |
| Typical use | Simple display, passing the result to a refresh function | Transforming or combining results |
The last row of the table matters later. Refreshing a GraphQL result with refreshGraphQL needs the whole result object, so you will wire to a property when you want to refresh.
Reactive parameters
A parameter is reactive when its value in the configuration object is a string that starts with $. The text after the $ names a property on the component. The platform reads that property and passes its value to the adapter.
@wire(getRecord, { recordId: '$recordId', fields: [NAME_FIELD] })In this configuration, '$recordId' means "use the current value of this.recordId". The fields value has no $, so it is passed as written.
Three rules cover most of the behavior:
- Only top-level properties work.
'$record.id'is not supported. Use a getter that returns the value instead, and name the getter in the string. - The platform reruns the wire when the value changes. The adapter is called again with the new configuration, and the target receives the new result.
- An
undefinedvalue delays the wire. If any reactive parameter isundefined, the adapter is not provisioned. Once the value becomes defined, the wire runs.
Rule 3 is useful when a value arrives later, for example from a parent component or a user choice. It is also a frequent source of confusion. If a wire never fires, check whether a reactive value is still undefined. A value of null is different. It is a defined value and is passed to the adapter.
Reactive values from getters
Getters let you compute a configuration value. This pattern is central to the GraphQL adapter, because the query variables are usually built as an object in a getter.
import { LightningElement, wire } from 'lwc';
import { getRecord } from 'lightning/uiRecordApi';
export default class DynamicFields extends LightningElement {
recordId = '001000000000001AAA';
includeIndustry = false;
@wire(getRecord, { recordId: '$recordId', fields: '$fieldList' })
account;
get fieldList() {
const fields = ['Account.Name'];
if (this.includeIndustry) {
fields.push('Account.Industry');
}
return fields;
}
toggleIndustry() {
this.includeIndustry = !this.includeIndustry;
}
}When toggleIndustry runs, includeIndustry changes. The getter now returns a different array, so the wire reruns with the new field list.
What counts as a change
LWC tracks property changes so it can rerun wires and rerender templates. Understanding the rules prevents two common bugs.
- Class fields are reactive. Since Spring '20, every field in a component class is reactive. Reassigning a field, such as
this.after = 'abc', triggers a rerun of any wire that depends on it. - Mutation of objects is shallow. Reassigning a field is detected. Changing a property deep inside an object, such as
this.filters.status = 'Open', is not detected for a plain object field unless you decorate the field with@track. The safest habit is to build a new object and assign it.
The second point matters for the GraphQL adapter. If your variables live in an object field, replace the whole object instead of editing it:
// Detected: a new object is assigned
this.filters = { ...this.filters, status: 'Open' };
// Not reliably detected: an in-place edit
this.filters.status = 'Open';A getter that builds a fresh object from simple fields avoids the problem. Each field is a primitive, and reassigning it triggers the rerun.
Lifecycle and timing
The wire service ties into the component lifecycle.
- The component is created, and the constructor runs. Wire results are not available yet.
- The component is inserted into the DOM and
connectedCallbackruns. The first wire provisioning happens around this point. - Results arrive, possibly more than once. The target receives each one, and the component rerenders.
- When a reactive value changes, the wire reruns and the target receives a new result.
- When the component is removed from the DOM, the wire is disconnected.
The diagram shows one cycle, from a reactive change to a rerender.
Because results can arrive after the first render, write templates that handle the empty state. Use lwc:if to render a section only when data exists, and show a loading or error message otherwise.
Common errors
These problems appear often in wired components.
| Symptom | Likely cause | Fix |
|---|---|---|
| The wire never fires | A reactive value is `undefined` | Give the field an initial value, or check that the parent sets it |
| The wire fires with stale values | The configuration value lacks the `$` prefix | Write `'$name'` so the platform reads the property |
| Nested value is ignored, such as `'$record.id'` | Only top-level properties are supported | Use a getter and reference it as `'$recordId'` |
| Changing an object property does not rerun the wire | In-place mutation is not detected | Assign a new object |
| The template throws on `data.fields` | The target is `undefined` before the first result | Use optional chaining or `lwc:if` |
| Function target runs twice | New results arrive on change or refresh | Make the function idempotent |
How this connects to the GraphQL adapter
The graphql adapter follows all of these rules. You will use it with a configuration that has two keys:
query, the GraphQL document, written with thegqltag.variables, an object of values for the query, usually passed as a reactive string such as'$variables'that names a getter.
When a value that feeds the variables getter changes, the wire reruns the query. This is how paging and filtering will work in later chapters. The adapter also returns an errors array instead of a single error. The error handling chapter covers that difference. The property or function target choice you saw above applies to the adapter in the same way.
import { LightningElement, wire } from 'lwc';
import { gql, graphql } from 'lightning/uiGraphQLApi';
export default class Preview extends LightningElement {
pageSize = 10;
@wire(graphql, {
query: gql`
query preview($first: Int) {
uiapi {
query {
Account(first: $first) {
edges { node { Id } }
}
}
}
}
`,
variables: '$variables'
})
result;
get variables() {
return { first: this.pageSize };
}
}You do not need to understand the query text yet. Notice the shape of the wire: an adapter, a configuration with a reactive '$variables' string, a getter that builds the value, and a property target that holds the result.
Summary of the model
- A wire links an adapter, a configuration, and a target.
- A property target keeps the whole result object. A function target receives
dataanderroreach time. - A
$namestring makes a parameter reactive. Only top-level properties are supported. - A wire waits while any reactive value is
undefined. - Reassigning a field triggers a rerun. Editing inside an object does not.
- The
graphqladapter uses the same model, withqueryandvariables.
Exercise
A component has the field filters = { status: 'Open' } and a wire configured with variables: '$variables', where the getter variables returns { status: this.filters.status }. A button handler runs this.filters.status = 'Closed', but the wire does not rerun. Why does it fail, and how do you fix it?
Show answer
The handler edits a property inside an object in place. LWC does not reliably detect that mutation for a plain object field, so the getter is not re-evaluated and the wire does not rerun. Fix it by assigning a new object, for example this.filters = { ...this.filters, status: 'Closed' };, or by storing status in its own primitive field and reassigning that.
Exercise
You wire getRecord with recordId: '$recordId', and the field recordId is declared without an initial value. The wire never returns data, even though a parent component sets recordId after a user action. Is this a bug? What happens when the parent sets the value?
Show answer
It is expected behavior, not a bug. While recordId is undefined, the wire service does not provision the adapter. Once the parent sets a defined value, the wire runs and the target receives the result. The template should handle the empty state in the meantime, for example with lwc:if.
Exercise
You want to refresh a result later with a function that needs the whole wire result object. Should you wire to a property or to a function, and why?
Show answer
Wire to a property. The property holds the complete result object. A function target receives only the destructured keys for each result, so you would have no stored object to pass to the refresh function.