Newer Version Available
Best Practices for Using GraphQL in LWC Offline
In addition to the general best practices detailed in GraphQL Wire Adapter Best Practices, we want to call your attention to two specific practices that are especially important for the Offline GraphQL implementation.
Provide Query and Variables via Getter Function
To make the results of a GraphQL query primable, you must use a specific structure in your code. This structure is specifically required for the GQL query to be discovered and processed by the static analyzer used by the priming subsystem. Do not inline the query with your wire adapter function definition.
For example, this code results in a query that can be analyzed and primed:
1// BEST PRACTICE
2// This GQL query can be primed
3@wire(graphql, {
4 query: '$myQuery',
5 variables: '$myVariables'
6})
7wiredData;
8
9get myQuery() {
10 return gql`query getSomeAccount($recordId: ID) {
11 uiapi { query { Account(...) { } } }`;
12}
13get myVariables() { return { recordId: '...' } }In contrast, this example behaves the same as the preceding code, as long as you’re online, but does not result in the wire adapter results being primed. If the required data and metadata isn’t primed by some other mechanism, it won’t function while you’re offline.
1// ANTI-PATTERN
2// This inline GQL query cannot be primed
3@wire(graphql, {
4 query: gql`query getSomeAccount($recordId: ID) {
5 uiapi { query { Account(...) { } } }`,
6 variables: {recordId: '...'}
7})
8wiredData;Delay Query Execution
This best practice is closely related to using getters to provide the GQL query string and variables, and uses the same code structures. It’s similarly essential to maximizing the completeness of priming activities performed by the mobile app prior to going offline. The details are described in Delay Query Execution in the GraphQL API Developer Guide.
Query Only the Data You Need
You can write a query that satisfies your data needs and gives you exactly what you asked for, nothing more and nothing less. Writing a brief query that satisfies your data requirements makes the return result predictable, while ensuring that your query remains performant.
See Query Only the Data You Need in the GraphQL API Developer Guide for an example on how to use pagination to avoid loading a large number of records in a single query.