How do you update the Apollo cache after a mutation?
Answer
When a mutation creates or deletes items (not just updates), the Apollo cache doesn't automatically know to update list queries. Three approaches: (1) Refetch queries: simplest — refetch affected queries after mutation: useMutation(ADD_TODO, { refetchQueries: [GET_TODOS] }). Causes an extra network request. (2) Cache update function: manually update the cache: update(cache, { data: { addTodo } }) { cache.modify({ fields: { todos(existing) { return [...existing, cache.writeFragment({ data: addTodo, fragment: TODO_FIELDS })]; } } }); }. (3) Cache invalidation: evict specific cache entries: cache.evict({ id: cache.identify(deletedItem) }); cache.gc();. The cache.modify approach is most fine-grained. For complex pagination, the mergeFunction in typePolicies handles automatic merging.
Previous
What is the difference between network-only, cache-first, and cache-and-network fetch policies?
Next
What is the graphql-tag (gql) utility?
More GraphQL Questions
View all →- Intermediate How do you implement pagination in GraphQL?
- Intermediate What is the Relay specification in GraphQL?
- Intermediate How do you implement authorization in GraphQL resolvers?
- Intermediate What is graphql-shield and how does it work?
- Intermediate How do you implement real-time subscriptions with GraphQL?