This LWC shows how to retrieve contact data based on a dynamic search string for a GraphQL query with the GraphQL wire adapter.
<aside>
📂 You can find the component in this folder: force-app\\main\\default\\lwc\\graphqlVariables
.
</aside>
<aside> 💡 If not familiar with using the GraphQL wire adapter, review this section: Using GraphQL in LWC and with wire adapter .
</aside>
When using the GraphQL wire adapter, some imports
are required:
import { gql, graphql } from 'lightning/uiGraphQLApi';
The syntax for using the wire adapter is as follows:
...
@wire(graphql, {
query: gql`
query searchContacts($searchKey: String!, $limit: Int = 5) {
uiapi {
query {
Contact(
where: { Name: { like: $searchKey } }
first: $limit
orderBy: { Name: { order: ASC } }
) {
edges {
node {
Id
Name {
value
}
}
}
}
}
}
}
`,
variables: '$variables'
})
contacts;
...
The Contact
object is being queried to get the first 5 contacts by name in ascended order.
The fields retrieved are inside the edges { node { ...
structure. The field Name
requires the value
attribute, as it might be exposing some other attributes.
The results from the adapter are wired to the contacts
property.
The function handler handleKeyChange
is used to avoid unnecessary calls to refresh the results introducing a delay. This is required because the variable searchKey
is used in the Graphql query as a parameter and for every change in this variable, the query is refreshed.
Allowing some delay between user keystrokes, we avoid sending continuous refresh requests for the query to get executed.
In the template, there is an iteration of the contacts
property when having results.
For every iteration, the contact name is shown accessing the result from the GraphQL result as contact.node.Name.value
.
...
<template lwc:if={contacts.data}>
<template
for:each={contacts.data.uiapi.query.Contact.edges}
for:item="contact"
>
<p key={contact.node.Id}>{contact.node.Name.value}</p>
</template>
</template>
...