Sub topic 13
Going further: aggregates and mutations
This chapter covers two features that sit next to everything you have built so far. Aggregate queries let you compute counts, sums, and averages on the server. Mutations change data. They also differ from reads in how a component runs them.
It assumes you can write a @wire(graphql) query, read edges and node, pass reactive variables, and call refreshGraphQL. The chapter is an overview. It shows the shape of each feature and the decisions around it, and it does not cover every argument.
Where these features fit
The uiapi schema has more than one entry point under the root. You have used uiapi { query { ... } } for records. Two other entry points follow the same naming style.
| Entry point | Purpose | Runs through the wire adapter? |
|---|---|---|
| `uiapi { query { Account { ... } } }` | Read records | Yes |
| `uiapi { aggregate { Account { ... } } }` | Read computed values over records | Yes |
| `uiapi { AccountCreate(...) { ... } }` (a mutation) | Create, update, or delete records | No, see below |
Aggregate queries
A normal query returns one node per record. An aggregate query returns one node per group, and each node holds computed values. Suppose you want the total opportunity amount for each stage. You could fetch every opportunity and add them up in JavaScript. That wastes bandwidth, and it breaks once the result is larger than a page. An aggregate query asks Salesforce to do the work.
The shape of an aggregate query
The query goes under uiapi { aggregate { ... } }. Inside, you name the object, optionally pass groupBy, and select an aggregate field on each node.
import { LightningElement, wire } from 'lwc';
import { gql, graphql } from 'lightning/uiGraphQLApi';
export default class PipelineByStage extends LightningElement {
rows = [];
errors;
@wire(graphql, {
query: gql`
query pipelineByStage {
uiapi {
aggregate {
Opportunity(groupBy: { StageName: { group: true } }) {
edges {
node {
aggregate {
StageName { value }
Amount { sum { value } }
Id { count { value } }
}
}
}
}
}
}
}
`
})
wiredPipeline({ data, errors }) {
if (data) {
this.rows = data.uiapi.aggregate.Opportunity.edges.map(({ node }, index) => ({
key: String(index),
stage: node.aggregate.StageName.value,
total: node.aggregate.Amount.sum.value,
count: node.aggregate.Id.count.value
}));
this.errors = undefined;
} else if (errors) {
this.errors = errors;
this.rows = [];
}
}
}Four details matter here.
- The extra
aggregatelevel. The values are undernode.aggregate, not directly onnode. A node in an aggregate result is a group, not a record. groupBychooses the groups.StageName: { group: true }produces one node per distinct stage. If you leavegroupByout, you get a single node that summarizes the whole result.- The function is part of the path.
Amount { sum { value } }reads the sum ofAmount. Other functions follow the same pattern, such asavg,min,max, andcount. The set of functions available depends on the field type. Numeric functions apply to numeric fields, and a text field will not offersum. - There is no record
Idto use as a key. A group is not a record, so the code builds akeyfrom the array index. For a stable key, use the grouped value instead, such as the stage name, when it is unique.
Values can be null
An aggregate over no matching rows, or over a field that is empty on every row, can produce null for the value. Guard before formatting:
const total = node.aggregate.Amount.sum.value ?? 0;Use the same defensive style you used for displayValue earlier. Do not assume that a number is always present.
Filtering and ordering aggregates
Aggregate queries accept where the same way record queries do. Use it to narrow the rows before they are grouped, for example to include only open opportunities. Ordering groups by a computed value is also possible through orderBy, with the aggregate function in the path. Check the schema in your org for the exact input type, because the available options vary by object and API version.
When to choose an aggregate query
| Situation | Better choice |
|---|---|
| You need a total, count, or average over many records | Aggregate query |
| You need the records themselves, even if you also total them | Record query, and sum in JavaScript if the result is small |
| You need totals plus per-record detail | Two wired queries, one of each |
| You need a statistic that spans a very large table | Aggregate query, with a `where` that keeps the scan small |
Do not fetch ten thousand records to show one number.
Mutations
A mutation is a GraphQL operation that changes data. The uiapi schema defines mutations for creating, updating, and deleting records. They are named after the object and the action, for example AccountCreate, AccountUpdate, and AccountDelete.
mutation createAccount($name: String) {
uiapi {
AccountCreate(input: { Account: { Name: $name } }) {
Record {
Id
Name { value }
}
}
}
}The mutation asks for fields back, using the same value wrapper you know from queries. That means the response can be used to update the screen without a second read.
Why not use @wire?
The wire service is for reads. A wired adapter runs when the component connects and again when a reactive parameter changes. It is meant to be free of side effects, because the platform decides when to call it and can call it more than once. A mutation has a side effect, so it must run only when you decide, such as in a click handler. That is why the @wire(graphql) adapter accepts queries and not mutations.
Running a GraphQL mutation is an imperative call. The function name and the module that exports it have changed between API versions. Check the Lightning Web Components developer guide for the version your org runs before you write it.
A safe pattern that works today: the record API plus a refresh
The lightning/uiRecordApi module has had createRecord, updateRecord, and deleteRecord for a long time. You can use them for the write and use refreshGraphQL to make your wired query pick up the change. This is the pattern most existing components use, and it keeps working however the mutation API evolves.
import { LightningElement, wire } from 'lwc';
import { gql, graphql, refreshGraphQL } from 'lightning/uiGraphQLApi';
import { createRecord } from 'lightning/uiRecordApi';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
export default class AccountCreator extends LightningElement {
name = '';
@wire(graphql, {
query: gql`
query latestAccounts {
uiapi {
query {
Account(first: 5, orderBy: { CreatedDate: { order: DESC } }) {
edges { node { Id Name { value } } }
}
}
}
}
`
})
graphqlResult;
get accounts() {
return this.graphqlResult?.data?.uiapi.query.Account.edges.map(({ node }) => ({
id: node.Id,
name: node.Name.value
})) ?? [];
}
handleNameChange(event) {
this.name = event.target.value;
}
async handleCreate() {
try {
await createRecord({
apiName: 'Account',
fields: { Name: this.name }
});
this.name = '';
await refreshGraphQL(this.graphqlResult);
} catch (error) {
this.dispatchEvent(
new ShowToastEvent({
title: 'Could not create the account',
message: error?.body?.message ?? 'Unknown error',
variant: 'error'
})
);
}
}
}The order of the steps matters. The component awaits the write first, and only then calls refreshGraphQL. If it refreshed first, the query would read the old data. The refreshGraphQL call takes the whole wire result object, which is why the wire result is stored in a property instead of being destructured in a handler.
Handling write errors
A failed write is not a partial read. Treat it as a failure of the whole action.
- Catch the rejection and show the user a message. Do not leave the form looking successful.
- Do not refresh after a failure, since nothing changed.
- Remember that sharing rules, field-level security, and validation rules apply to writes as well as reads. A user who can read a field cannot necessarily edit it.
Common mistakes
- Reading aggregate values from
nodedirectly. The values are undernode.aggregate. A query that selects fields on the node itself will fail validation. - Using the array index as a key for data that reorders. If groups can change order between refreshes, use the grouped value as the key.
- Summing paged records in JavaScript. A total over one page of results is not a total over the data. Use an aggregate query.
- Putting a mutation in
@wire. Wire adapters are for reads. Run writes from an event handler. - Forgetting to refresh. The wired query keeps its cached result until something refreshes it. After a write, call
refreshGraphQLwith the wire result.
Summary of the decision
Use a record query when you want rows. Use an aggregate query when you want a number about many rows. Use an event handler, not a wire, for anything that changes data, and refresh the wired result after the change succeeds.
Exercise
A component shows the number of open opportunities for each stage. A developer wires a record query with first: 200 and counts the nodes per stage in JavaScript. The org has 5,000 open opportunities. Explain what is wrong, and describe the replacement query, including where the count appears in the result.
Show answer
The counts are wrong because the query returns at most 200 records, so each stage's count only reflects the first page. The fix is an aggregate query under uiapi { aggregate { Opportunity(...) } }. Add a where that keeps only open opportunities, set groupBy: { StageName: { group: true } }, and select aggregate { StageName { value } Id { count { value } } } on each node. The count for each stage is then at node.aggregate.Id.count.value, and the stage name is at node.aggregate.StageName.value.
Exercise
A user clicks Save, the handler calls createRecord, and then calls refreshGraphQL(this.graphqlResult) without awaiting the first call. The list sometimes does not show the new record. Why, and how do you fix it?
Show answer
The refresh can run before the write has finished, so the query reads data that does not include the new record yet. Await createRecord and call refreshGraphQL only after it resolves. Put both inside a try/catch so a failed write shows an error and skips the refresh.