Use the variables configuration parameter of the graphql wire adapter to supply dynamic values to your GraphQL query.
tip: The graphqlVariables component in the lwc-recipes repo returns contact data based on a dynamic search string.
Implement GraphQL Variables in LWC
Let’s say you have a component that displays a dropdown with several options to represent different annual revenue amounts. Selecting an amount returns the accounts whose annual revenue is greater or equal to the amount. In this example, the $minAmount GraphQL variable enables the component to set and change the minimum amount, displaying the corresponding records when the value changes.
//accountsGQL.js
import { LightningElement, wire } from "lwc";
import { gql, graphql } from "lightning/graphql";
export default class AccountsGQL extends LightningElement {
records;
errors;
minAmount = "5000000";
minAmounts = [
{ label: "All", value: "0" },
{ label: "$5,000,000", value: "5000000" },
{ label: "$50,000,000", value: "50000000" },
{ label: "$500,000,000", value: "500000000" },
];
@wire(graphql, {
query: gql`
query bigAccounts($minAmount: Currency) {
uiapi {
query {
Account(where: { AnnualRevenue: { gte: $minAmount } }) {
edges {
node {
Id
Name {
value
}
AnnualRevenue {
displayValue
}
}
}
}
}
}
}
`,
variables: "$variables", // Use a getter function to make the variables reactive
})
graphqlQueryResult({ data, errors }) {
if (data) {
this.records = data.uiapi.query.Account.edges.map((edge) => edge.node);
}
this.errors = errors;
}
get variables() {
return {
minAmount: this.minAmount,
};
}
// Called when the user selects a new minimum amount
handleMinAmountChange(event) {
this.minAmount = event.detail.value;
}
}
Next, create the dropdown in your component to enable input selection. Selecting an option on the dropdown triggers the handleMinAmountChange function and sets the new value on the minAmount variable, which updates the query results based on the selected amount.
<!-- accountsGQL.html -->
<template>
<lightning-card title="accountsGQL" icon-name="standard:account">
<div class="slds-var-m-horizontal_medium">
<lightning-combobox
name="minAmount"
label="Amount"
value={minAmount}
placeholder="Select a minimum amount"
options={minAmounts}
onchange={handleMinAmountChange}
></lightning-combobox>
<template lwc:if={records}>
<template for:each={records} for:item="account">
<div class="card-spacer" key={account.Id}>
<lightning-card icon-name="standard:account">
<h1 slot="title">{account.Name.value}</h1>
{account.AnnualRevenue.displayValue}
</lightning-card>
</div>
</template>
</template>
</div>
</lightning-card>
</template>
GraphQL variables allow your query to use values that aren’t known until run time. They also reduce the size of your component by eliminating the need for multiple queries that are near-duplicates.
note: GraphQL variables can’t be used to pass the names of objects or fields. This is a limitation of the GraphQL syntax and the way the Salesforce GraphQL schema is designed.