Sub topic 6
Using reactive variables
This chapter assumes you can write a Lightning web component with a JavaScript class and an HTML template. It also assumes you know how @wire and reactive properties work, and that you have run a basic graphql wire query. Here you will learn how query variables work and how they make a wired query rerun.
Why variables exist
A query can hard-code every value, such as first: 10. That works until the user changes something: a page size, a search term, a selected industry. Without variables you would have to build a new query string each time.
GraphQL solves this with variables. You declare them in the query signature, reference them with a $ prefix, and supply their values separately. The query text stays fixed. Only the values change.
With the graphql wire adapter, you pass the values through the variables config property. If that property is reactive, the wire service reruns the query whenever the values change.
Declaring and using a variable
A variable has three parts in the query:
- A declaration in the operation signature:
query accountList($first: Int). - A type after the colon:
Int,String,Boolean, and so on. - A use inside the query body:
Account(first: $first).
import { LightningElement, wire } from 'lwc';
import { gql, graphql } from 'lightning/uiGraphQLApi';
export default class AccountList extends LightningElement {
accounts = [];
errors;
@wire(graphql, {
query: gql`
query accountList($first: Int) {
uiapi {
query {
Account(first: $first, orderBy: { Name: { order: ASC } }) {
edges {
node {
Id
Name { value }
Industry { value displayValue }
}
}
}
}
}
}
`,
variables: '$variables'
})
wiredAccounts({ data, errors }) {
if (data) {
this.accounts = data.uiapi.query.Account.edges.map(({ node }) => ({
id: node.Id,
name: node.Name.value,
industry: node.Industry.displayValue ?? node.Industry.value
}));
this.errors = undefined;
} else if (errors) {
this.errors = errors;
this.accounts = [];
}
}
get variables() {
return { first: 10 };
}
}The wire config contains variables: '$variables'. The string '$variables' is the standard reactive-parameter syntax in LWC. It tells the wire service to read this.variables and to watch it. Because variables is a getter that returns an object, the component supplies the whole variable set in one place.
The template for this component renders the mapped list and shows a message if errors is set.
<template>
<lightning-card title="Accounts" icon-name="standard:account">
<template lwc:if={errors}>
<p class="slds-p-around_medium">The accounts could not be loaded.</p>
</template>
<ul class="slds-p-around_medium">
<template for:each={accounts} for:item="account">
<li key={account.id}>{account.name} ({account.industry})</li>
</template>
</ul>
</lightning-card>
</template>How a rerun happens
The wire service tracks the reactive value behind '$variables'. When that value changes, the service calls the adapter again with the new variables. The adapter fetches fresh data, and your wired function runs again with the new result.
The important detail is what counts as a change. The getter reads other component fields, such as this.pageSize. When one of those fields is reassigned, the getter returns a new object, and the wire service sees a new value.
get variables() {
return { first: this.pageSize, after: this.after };
}In this getter, pageSize and after are fields on the class. In LWC, class fields are reactive for reassignment. If a handler runs this.pageSize = 20, the template and the wire both react.
The flow looks like this:
Variables in a working example
Cursor pagination is a good place to see variables at work. The query takes two variables, $first and $after. Changing after fetches the next page.
import { LightningElement, wire } from 'lwc';
import { gql, graphql } from 'lightning/uiGraphQLApi';
export default class AccountPager extends LightningElement {
pageSize = 5;
after = null;
accounts = [];
pageInfo = { hasNextPage: false, endCursor: null };
@wire(graphql, {
query: gql`
query pagedAccounts($first: Int, $after: String) {
uiapi {
query {
Account(first: $first, after: $after, orderBy: { Name: { order: ASC } }) {
edges { node { Id Name { value } } }
pageInfo { hasNextPage endCursor }
}
}
}
}
`,
variables: '$variables'
})
wiredPage({ data }) {
if (data) {
const result = data.uiapi.query.Account;
this.accounts = result.edges.map(({ node }) => ({ id: node.Id, name: node.Name.value }));
this.pageInfo = result.pageInfo;
}
}
get variables() {
return { first: this.pageSize, after: this.after };
}
handleNext() {
if (this.pageInfo.hasNextPage) {
this.after = this.pageInfo.endCursor;
}
}
}When the user triggers handleNext, the handler assigns this.after. The variables getter now returns { first: 5, after: '<cursor>' }. The wire service reruns the query, and wiredPage receives the next five accounts. Chapter on pagination covers cursors in detail. Here the point is the mechanism: you never call the query yourself. You change state, and the wire reruns.
Rules for variables
Several rules apply to variables in this adapter.
- Every variable you use in the query must be declared in the operation signature, with a type.
- A type followed by
!, such asString!, means the variable is required. If you omit it, the query fails. - A type without
!, such asInt, is optional. Passingnullor leaving it out is allowed. - Variable names in the
variablesobject must match the declared names without the$. Declare$first, supplyfirst. - Values must match the declared type. Passing a string to an
Intvariable produces an error.
Undefined variables and delayed queries
A reactive config property that is undefined pauses a wire. Many wire adapters in LWC do not run until all their reactive parameters are defined. Use this when a query depends on something the user has not chosen yet.
Plan for this behavior in two ways:
- If you want the query to run immediately, make sure the getter always returns an object.
- If you want to delay the query, return
undefinedfrom the getter until the inputs are ready.
get variables() {
if (!this.selectedIndustry) {
return undefined;
}
return { industry: this.selectedIndustry };
}Test this in your own org rather than assuming it. If your component shows no data and no error, an undefined config is one of the first things to check.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| The query never runs | The `variables` getter returns `undefined` | Return an object, or wait until inputs are ready on purpose |
| The query does not rerun after a change | The field was mutated in place, not reassigned | Assign a new value, or return a new object from the getter |
| An error about an unknown variable | The query uses `$name` that is not declared in the signature | Add the declaration with a type |
| An error about a type mismatch | The value does not match the declared type | Convert the value, for example with `Number()` for an `Int` |
| A required variable error | A `!` variable was omitted or `null` | Supply a value, or remove the `!` |
Converting input values
Values from lightning-input and lightning-combobox arrive as strings. An Int variable needs a number, so convert before storing.
handlePageSizeChange(event) {
const size = Number(event.detail.value);
if (Number.isInteger(size) && size > 0) {
this.pageSize = size;
}
}Checking the value first keeps an invalid entry from triggering a failing query.
Variables and resetting state
When a filter changes, any cursor you saved belongs to the old query. Reusing it can return wrong pages or errors. Reset paging state in the same handler that changes the filter.
handleIndustryChange(event) {
this.selectedIndustry = event.detail.value;
this.after = null;
}Both fields change in one handler, so the wire service sees one updated config on the next render cycle and runs one query, not two.
What variables cannot do
Variables supply values. They do not change the shape of the query. You cannot use a variable to choose which fields to select or which object to query. If you need a different set of fields or a different object, you need a different query. Variables also do not replace where and orderBy structure; they fill in values inside that structure. The next chapter shows how.
Exercise
A component declares query accounts($first: Int) and sets variables: '$variables'. A handler runs this.variables.first = 20, where variables is a plain field holding { first: 10 }. The list does not update. Why, and how do you fix it?
Show answer
The handler mutated a property inside the existing object, so the reactive value the wire watches did not change. Reassign instead, for example this.variables = { first: 20 };, or keep pageSize as a field and have a variables getter return { first: this.pageSize }, then assign this.pageSize = 20.
Exercise
You add an $after: String variable for paging and let the user change an industry filter. After changing the filter, the list shows odd results. What should the filter handler also do?
Show answer
Reset after to null in the same handler. The saved cursor belongs to the previous query, so the new query should start from the first page.