⬡ GraphQL Intermediate

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.