Apollo 6: Cache Read & Write
easy⏱ 5 mincourseapollo
Direct cache manipulation
Apollo exposes four key methods for direct cache access:
- readQuery / writeQuery — Read or write an entire query result in the cache. Great for updating list queries after a mutation.
- readFragment / writeFragment — Read or write a single entity by its cache ID (e.g.,
User:5). Perfect for updating one field on one object.
- cache.modify — The most surgical option. Modify individual fields on a cached entity without needing to know the full query shape.
All these methods trigger re-renders in components that depend on the affected data.
// Read a cached query result
const data = client.readQuery({ query: GET_TODOS });
// Write updated data back
client.writeQuery({
query: GET_TODOS,
data: { todos: [...data.todos, newTodo] },
});
Manually update cache after action
Create a TodoManager component. After adding a todo via mutation, use cache.writeQuery inside the update callback to append the new todo to the cached list. Also implement a "Mark Complete" button that uses cache.modify to toggle the completed field directly in cache without a network request.
cache.modify for surgical updates
When you need to change one field on one object, cache.modify is the cleanest approach. It takes the cache ID (like Todo:5) and a fields object where each key is a field name and the value is a modifier function. The modifier receives the current cached value and returns the new value. No need to read/write the full query shape.
cache.modify({
id: cache.identify(todo),
fields: {
completed(prev) {
return !prev;
},
},
});
When to use each method
Use writeQuery when updating list queries (add/remove items). Use writeFragment when updating a single entity's fields (e.g., toggling a boolean). Use cache.modify when you want the most precise control and don't want to read the existing data first. Use readQuery to check the current cache state before writing. Always prefer the least invasive method — cache.modify > writeFragment > writeQuery.