Sub topic 11
Refreshing results after changes
A wired GraphQL query runs when the component connects, and again when a reactive variable changes. It does not rerun when data changes on the server. This chapter shows how to refresh a result on demand with refreshGraphQL, and how to avoid the mistakes that make the call do nothing.
This chapter assumes you have read the earlier chapters. You should be able to write a query with gql, wire it with @wire(graphql), and read edges, node, and value from the result. It also assumes you know how reactive variables rerun a query.
Why a wired result goes stale
The graphql adapter returns results from a client-side cache that Lightning Data Service manages. The cache is what makes repeat queries fast. It also means the component shows what it received the last time the query ran.
The cache can fall behind when:
- Your component creates or changes a record, for example with
createRecord, or by calling an Apex method. - A Flow, a trigger, another user, or another component changes the same records.
- A child component saves data, and the parent that owns the query has no signal that anything happened.
Do not assume the cache will update itself. After you change data and need to see it in a wired query, refresh that query explicitly.
The working model
refreshGraphQL is a named export of lightning/uiGraphQLApi, next to gql and graphql.
import { gql, graphql, refreshGraphQL } from 'lightning/uiGraphQLApi';You call it with the full result object that the wire service gave you. It returns a promise. When the promise resolves, the query has been rerun and the wire has delivered fresh data to the component.
The important point is "full result object". The wire result has data and errors, and it also carries extra information the adapter needs to identify which query to refresh. If you pass only data, the adapter cannot find the query, and the refresh does nothing useful.
The refresh reuses the query and the variables the wire is currently using. You don't pass either one again.
Pattern 1: wire to a property
The simplest way to keep the full result is to wire the adapter to a property instead of a function. The property then holds the whole result object, and you can hand it straight to refreshGraphQL.
The next example saves a new account, then refreshes a list of the five most recently created accounts.
import { LightningElement, wire } from 'lwc';
import { createRecord } from 'lightning/uiRecordApi';
import { gql, graphql, refreshGraphQL } from 'lightning/uiGraphQLApi';
export default class RecentAccounts extends LightningElement {
newName = '';
saveError;
@wire(graphql, {
query: gql`
query recentAccounts {
uiapi {
query {
Account(first: 5, orderBy: { CreatedDate: { order: DESC } }) {
edges {
node {
Id
Name { value }
}
}
}
}
}
}
`
})
graphqlResult;
get accounts() {
return (
this.graphqlResult?.data?.uiapi.query.Account.edges.map(({ node }) => ({
id: node.Id,
name: node.Name.value
})) ?? []
);
}
handleNameChange(event) {
this.newName = event.target.value;
}
async handleAdd() {
this.saveError = undefined;
try {
await createRecord({
apiName: 'Account',
fields: { Name: this.newName }
});
this.newName = '';
await refreshGraphQL(this.graphqlResult);
} catch (error) {
this.saveError = error;
}
}
}<template>
<lightning-card title="Recent accounts" icon-name="standard:account">
<div class="slds-p-around_medium">
<lightning-input
label="New account name"
value={newName}
onchange={handleNameChange}
></lightning-input>
<lightning-button
label="Add account"
onclick={handleAdd}
></lightning-button>
<template lwc:if={saveError}>
<p>The account could not be saved.</p>
</template>
<ul>
<template for:each={accounts} for:item="account">
<li key={account.id}>{account.name}</li>
</template>
</ul>
</div>
</lightning-card>
</template>Three details matter here:
graphqlResultis assigned by the wire service. It isundefineduntil the first response arrives, so the getter uses optional chaining and falls back to an empty list.await createRecord(...)finishes before the refresh starts. If you refresh first, the query can return before the new record exists.- The
tryblock covers both the save and the refresh. A failure in either one lands insaveError.
Pattern 2: wire to a function and keep the result
When you wire to a function, as in the earlier chapters, the function receives the result as its argument. If you destructure it in the parameter list, as in wired({ data, errors }), you lose the full object. To refresh from a function handler, keep a reference to the whole argument.
import { LightningElement, wire } from 'lwc';
import { gql, graphql, refreshGraphQL } from 'lightning/uiGraphQLApi';
export default class AccountListWithRefresh extends LightningElement {
accounts = [];
errors;
wiredResult;
@wire(graphql, {
query: gql`
query accountList($first: Int) {
uiapi {
query {
Account(first: $first, orderBy: { Name: { order: ASC } }) {
edges {
node {
Id
Name { value }
}
}
}
}
}
}
`,
variables: '$variables'
})
handleResult(result) {
this.wiredResult = result;
const { data, errors } = result;
if (data) {
this.accounts = data.uiapi.query.Account.edges.map(({ node }) => ({
id: node.Id,
name: node.Name.value
}));
this.errors = undefined;
} else if (errors) {
this.errors = errors;
this.accounts = [];
}
}
get variables() {
return { first: 10 };
}
async handleRefresh() {
if (this.wiredResult) {
await refreshGraphQL(this.wiredResult);
}
}
}The handler stores result first, then destructures it. The refresh method passes the stored object, not this.accounts and not data.
Choose between the two patterns this way:
| Situation | Better pattern |
|---|---|
| You only need the data to render, and a getter can reshape it | Property |
| You need to run code each time data arrives, such as copying fields or logging errors | Function with stored result |
| You need both | Function with stored result |
Refreshing and variables
A refresh reruns the query with the variables the wire is using at that moment. This has one consequence for paginated lists. If the user has moved to page three by setting after to a cursor, a refresh reloads page three, not page one. If you want the user to see the first page again, for example after adding a record that sorts to the top, reset the variables as well:
async handleAddAndReset() {
await createRecord({ apiName: 'Account', fields: { Name: this.newName } });
this.after = null; // changing a reactive variable reruns the wire on its own
}If after was already null, nothing changes, so no rerun happens. In that case call refreshGraphQL instead. A robust handler can do both: set after = null, and call the refresh only when the value was already null.
async reloadFirstPage() {
if (this.after === null) {
await refreshGraphQL(this.wiredResult);
} else {
this.after = null;
}
}Choosing a trigger
You can call refreshGraphQL from any code that knows data changed. Common triggers:
- After the component's own save, as in Pattern 1.
- On a button the user can press, such as "Refresh".
- When a child component dispatches a custom event, such as
saved, and the parent that owns the wire handles it. - On a timer, if you must poll. Keep the interval long, because each refresh is a server request that counts against your limits.
Prefer an event-driven refresh to a timer. A timer refreshes when nothing changed and misses changes that happen between ticks.
Common errors
- Passing
datainstead of the result.refreshGraphQL(this.data)has no way to identify the query. Pass the object the wire produced. - Destructuring in the handler signature and discarding the rest.
handleResult({ data, errors })leaves nothing to refresh with. Take the wholeresultparameter and store it. - Refreshing before the first response. The stored result is
undefineduntil the wire delivers. Guard withif (this.wiredResult). - Using
refreshApex. That function refreshes Apex wires. It does not work with the graphql adapter. UserefreshGraphQL. - Not awaiting the save. If the refresh starts while the save is in flight, the query may return the old data, and the list looks unchanged.
- Ignoring a rejected promise. A refresh can fail, for example on a network error. Wrap the call in
try/catchor add.catch(), and surface a message. - Expecting a refresh to change the query. It reruns the same query. To get different data, change a reactive variable.
Checking that it worked
When a refresh seems to do nothing, check in this order:
- Log the argument you pass to
refreshGraphQL. It should have the same shape as the wire's result, withdataorerrors. - Confirm the save finished before the refresh began.
- Confirm the changed record matches your query. A new account with an old
CreatedDate, or one that fails yourwherefilter, will not appear in the top five. - Check the user's access. A user who cannot see the record or a field will not get it back, however often you refresh.
Exercise
A developer wires a query with wired({ data, errors }) { this.accounts = ...; } and later calls refreshGraphQL(this.accounts) after saving a record. The list never updates. Give two problems and show how to fix them.
Show answer
First, the handler destructures the result and discards the full object, so the component has nothing to pass to the refresh. Second, this.accounts is a reshaped array, not the wire result, so the adapter cannot identify the query. The fix is to change the handler to wired(result) { this.wiredResult = result; const { data, errors } = result; ... } and call await refreshGraphQL(this.wiredResult) after the save finishes. Guard the call with if (this.wiredResult) so it does not run before the first response.
Exercise
A paginated account list sits on page three (after holds a cursor). The user adds an account that sorts to the top, and you want them to see it. Why does refreshGraphQL alone not show the new record, and what should the handler do?
Show answer
A refresh reruns the query with the current variables, so it reloads page three and the new record, which sorts to the first page, stays off screen. The handler should reset after to null. Changing a reactive variable reruns the wire by itself. If after is already null, nothing changes, so the handler should call refreshGraphQL with the stored result in that case.