Sub topic 4
Your first query with gql and @wire(graphql)
What you need before this chapter
This chapter assumes you can build a basic Lightning web component with a JavaScript class and an HTML template. It also assumes you know how @wire provisions data to a property or function, and you know what a GraphQL query, field, and argument are. Wire service reactivity and the uiapi schema were covered earlier in the series. Here you write a first complete query and run it.
By the end you will be able to:
- Import
gqlandgraphqlfrom the right module. - Attach a query to a component with
@wire(graphql). - Describe what the adapter hands back to your component.
- Recognize the mistakes that most often break a first query.
The two imports
Everything starts with one import statement.
import { gql, graphql } from 'lightning/uiGraphQLApi';The two names do different jobs:
| Name | What it is | Where you use it |
|---|---|---|
| `graphql` | The wire adapter | First argument of `@wire` |
| `gql` | A tagged template literal that parses query text | Value of the `query` config key |
gql turns the text between the backticks into a parsed query document. The adapter expects that document, not a raw string. If you pass a plain string to query, the adapter has nothing it can run.
Keep the text inside gql static. Do not splice values into it with ${...}. Dynamic values belong in query variables, which a later chapter covers. Keeping the text static lets the platform parse and cache the query document once.
What happens when the component loads
The component declares the query. The wire service runs it and sends results back to the component.
You never call the adapter yourself. Your component runs the query when it connects to the page, and again if a reactive parameter changes. The result is delivered to whatever the wire is attached to.
Anatomy of the query
Salesforce exposes its objects under a root field called uiapi. The structure below is the shape you will type many times.
| Level | Meaning |
|---|---|
| `uiapi` | Root of the Salesforce schema |
| `query` | Entry point for reading records |
| `Account` | The object you want. Use its API name. |
| `edges` | A list, with one entry per record |
| `node` | The record itself, holding the fields you ask for |
Each field you want from a record goes inside node. Simple fields such as Name are objects, not bare values, so you write Name { value }. The Id field is the exception and is requested by name alone. The next chapter explains value and displayValue in detail. For now, copy the pattern.
The first argument limits how many records come back. A query on Account without it still runs, but stating a page size makes your intent clear. Pagination gets its own chapter later.
Writing the component
This component lists five accounts. It has three files: JavaScript, HTML, and the metadata file.
import { LightningElement, wire } from 'lwc';
import { gql, graphql } from 'lightning/uiGraphQLApi';
export default class AccountSnapshot extends LightningElement {
accounts = [];
errors;
@wire(graphql, {
query: gql`
query accountSnapshot {
uiapi {
query {
Account(first: 5) {
edges {
node {
Id
Name { value }
}
}
}
}
}
}
`
})
wiredAccounts({ data, errors }) {
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 = [];
}
}
}<template>
<lightning-card title="Account snapshot" 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}</li>
</template>
</ul>
</lightning-card>
</template><?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>62.0</apiVersion>
<isExposed>true</isExposed>
<targets>
<target>lightning__AppPage</target>
<target>lightning__HomePage</target>
</targets>
</LightningComponentBundle>Deploy the bundle, then add the component to a Lightning page in an org that has Account records. You should see up to five account names.
What the wired function receives
The adapter passes one object to your function. It has two properties:
dataholds the query result. It mirrors the shape of your query, starting atuiapi. It isundefineduntil a result arrives.errorsholds an array of error objects when something went wrong. It isundefinedon success.
Your function can run more than once. It runs when the component first connects, and again whenever the result changes. That is why the example resets errors on success and accounts on failure. Without those resets, stale values from an earlier run would stay on screen.
The path data.uiapi.query.Account.edges follows your query line for line. If you can read the query, you can write the path.
Wiring to a property instead
You can wire to a property rather than a function. The property then receives the whole { data, errors } object, and you read from it in a getter.
import { LightningElement, wire } from 'lwc';
import { gql, graphql } from 'lightning/uiGraphQLApi';
export default class AccountNames extends LightningElement {
@wire(graphql, {
query: gql`
query accountNames {
uiapi {
query {
Account(first: 5) {
edges { node { Id Name { value } } }
}
}
}
}
`
})
result;
get accounts() {
return (
this.result?.data?.uiapi.query.Account.edges.map(({ node }) => ({
id: node.Id,
name: node.Name.value
})) ?? []
);
}
}The optional chaining (?.) matters here. The property is undefined before the first result, so reading .data directly would throw.
Choose between the two forms like this:
| Form | Choose it when |
|---|---|
| Wired function | You want to reshape data once and store it, as in the first example |
| Wired property | You want to keep the complete result, for example to pass it to `refreshGraphQL` later |
Running order and caching
The query runs after the component connects, not during construction. During the first render your tracked fields still hold their initial values. Give them safe defaults, such as an empty array, so the template renders cleanly while the request is in flight.
The adapter caches results. If two components on the page run the same query, the platform can serve the second one from cache. Cached results can go stale after records change elsewhere. A later chapter shows how to refresh them.
Common errors in a first query
Most first-query problems come from a small set of mistakes.
| Symptom | Likely cause | Fix |
|---|---|---|
| The component loads but nothing renders | The query is wrapped in a plain string, not `gql` | Use the `gql` tagged template |
| `Cannot read properties of undefined` | The code reads `data` before the first result arrives | Guard with `if (data)` or use `?.` |
| `Name` shows as `[object Object]` | The field was read without `.value` | Request `Name { value }` and read `node.Name.value` |
| `data.Account` is `undefined` | The path skipped the `uiapi` and `query` levels | Use `data.uiapi.query.Account` |
| The list is the wrong shape | The code mapped `edges` entries directly instead of their `node` | Destructure `{ node }` in the map |
| `errors` is set and `data` is empty | The query has a bad field name or the user cannot see the object | Check API names and the user's access |
Check the browser developer console for the full text of each entry in errors. The message usually names the field that failed validation.
A short debugging routine
When a query returns nothing, work through these steps in order:
- Confirm the import line reads
lightning/uiGraphQLApiand brings in bothgqlandgraphql. - Log the whole object in your wired function with
console.log(JSON.stringify({ data, errors })). - If
errorsis set, read its messages. A field-name typo is the most common cause. - If
datais set but the page is blank, compare your access path to the shape of the query. - Check that the running user can see records of that object.
Remove the logging when you are done.
Exercise
A developer writes query: '{ uiapi { query { Account(first: 5) { edges { node { Id } } } } } }' inside the @wire(graphql, { ... }) config, with no gql tag. What is wrong, and what is the fix?
Show answer
The query is a plain string. The adapter expects a parsed query document, which the gql tagged template produces. Import gql from lightning/uiGraphQLApi and write the query as gql... with backticks.
Exercise
Given a wired function wired({ data, errors }) for the query in this chapter, write the expression that returns the Name of the first account in data.
Show answer
data.uiapi.query.Account.edges[0].node.Name.value. The path follows the query: uiapi, query, Account, the first entry of edges, then node, then the Name field's value.
Exercise
Why does the property-wired example use this.result?.data?.uiapi... with ?. while the function-wired example only checks if (data)?
Show answer
A property wired to the adapter is undefined until the first result arrives, so reading .data on it would throw. The wired function is only called with an object that is already destructured, so it only needs to check whether data is present.