Sub topic 13
Going further: aggregates and mutations
This chapter assumes you can already write a @wire(graphql) query, read edges and node, pass reactive variables, and call refreshGraphQL. It covers two features outside the main flow: summarizing records with aggregates, and changing records with mutations. Both are availability-dependent, so check the release notes for your org's API version before relying on them.
Aggregates
An aggregate query returns computed values such as counts, sums, and averages. It does not return individual records. Aggregates live under uiapi.aggregate, a sibling of uiapi.query. Each object is queried the same way as before, but the node holds an aggregate object instead of record fields.
The following component totals open opportunity amounts by stage:
import { LightningElement, wire } from 'lwc';
import { gql, graphql } from 'lightning/uiGraphQLApi';
export default class StageTotals extends LightningElement {
totals = [];
errors;
@wire(graphql, {
query: gql`
query stageTotals {
uiapi {
aggregate {
Opportunity(
where: { IsClosed: { eq: false } }
groupBy: { StageName: { group: true } }
) {
edges {
node {
aggregate {
StageName { value }
Amount { sum { value } }
}
}
}
}
}
}
}
`
})
wiredTotals({ data, errors }) {
if (data) {
this.totals = data.uiapi.aggregate.Opportunity.edges.map(({ node }) => ({
stage: node.aggregate.StageName.value,
total: node.aggregate.Amount.sum.value
}));
this.errors = undefined;
} else if (errors) {
this.errors = errors;
this.totals = [];
}
}
}Note three differences from a record query:
groupBychooses the field to group on, andgroup: trueturns grouping on for it.- Each aggregate function (
sum,avg,min,max,count) wraps avalue, so you readAmount.sum.value. - The
whereargument works as it does in record queries. Filter first to keep the grouped set small.
Mutations
A mutation changes data. Mutations are not wired, because a wire reads data and reruns when its inputs change. You run a mutation on demand, for example from a button handler. LWC provides executeMutation in lightning/uiGraphQLApi for this. It takes the same query and variables shape as the wire config and returns a promise.
Mutation fields sit under uiapi, named after the object and the operation, such as AccountCreate, AccountUpdate, and AccountDelete.
import { LightningElement, wire } from 'lwc';
import { gql, graphql, executeMutation, refreshGraphQL } from 'lightning/uiGraphQLApi';
export default class AccountCreator extends LightningElement {
errorMessage;
@wire(graphql, {
query: gql`
query recentAccounts {
uiapi {
query {
Account(first: 5, orderBy: { CreatedDate: { order: DESC } }) {
edges { node { Id Name { value } } }
}
}
}
}
`
})
graphqlResult;
async handleCreate() {
const name = this.template.querySelector('lightning-input').value;
try {
const result = await executeMutation({
query: gql`
mutation createAccount($name: String) {
uiapi {
AccountCreate(input: { Account: { Name: $name } }) {
Record { Id Name { value } }
}
}
}
`,
variables: { name }
});
if (result.errors) {
this.errorMessage = result.errors.map((e) => e.message).join(', ');
return;
}
this.errorMessage = undefined;
await refreshGraphQL(this.graphqlResult);
} catch (error) {
this.errorMessage = error.message;
}
}
}The last step matters. A mutation does not update wired query results by itself. Call refreshGraphQL with the stored wire result so the list shows the new record.
Choosing a mutation approach
| Need | Reasonable choice |
|---|---|
| Create or edit one record from a form | `lightning-record-edit-form` |
| Change records and re-read them with the same query language | `executeMutation` plus `refreshGraphQL` |
| Complex logic or callouts | Apex |
Common errors
- Reading
errorsas an exception. A mutation can resolve with anerrorsarray and no thrown error. Check both, as the example does. - Forgetting to refresh. The data changed, but the wired list still shows the cached result.
- Treating aggregates as live per-record data. Re-run or refresh them after changes, the same as any other wired query.
Exercise
After a mutation succeeds, your wired list still shows the old data. What do you do, and what must you have kept to do it?
Show answer
Call refreshGraphQL with the wire result. You must have assigned the wire to a property, such as graphqlResult, so you hold the whole result object rather than only the destructured data.
Exercise
How do you read the summed Amount for a stage in an aggregate query result?
Show answer
Through node.aggregate.Amount.sum.value. The sum function wraps a value field, and the node holds an aggregate object instead of record fields.