In the update
hook of useMutation, Apollo's documentation recommends using writeFragment
to get an internal reference to a newly added object. I find this peculiar, as that object already exists in the cache. So I tested it with readFragment
and sure enough, it works well. Is there a preference to using writeFragment
over readFragment
in this use case?
https://www.apollographql.com/docs/react/data/mutations/#making-all-other-cache-updates
const [addTodo] = useMutation(ADD_TODO, {
update(cache, { data: { addTodo } }) {
cache.modify({
fields: {
todos(existingTodos = []) {
const newTodoRef = cache.writeFragment({
data: addTodo,
fragment: gql`
fragment NewTodo on Todo {
id
type
}
`
});
return [...existingTodos, newTodoRef];
}
}
});
Excerpt from that page:
With the help of cache.writeFragment we get an internal reference to the added todo, then store that reference in the ROOT_QUERY.todos array.
const [addComment] = useMutation(ADD_COMMENT, {
update(cache, { data: { addComment } }) {
cache.modify({
fields: {
comments(existingCommentRefs = [], { readField }) {
const newCommentRef = cache.writeFragment({
data: addComment,
fragment: gql`
fragment NewComment on Comment {
id
text
}
`
});
return [...existingCommentRefs, newCommentRef];
}
}
});
}
});
Excerpt from that page:
the comment was already added to the cache by useMutation. Consequently, cache.writeFragment returns a reference to the existing object.
I also posted this question on Apollo Client's discussion board (https://github.com/apollographql/apollo-client/discussions/7515), but didn't get a response there.
The benefit of using writeFragment
over readFragment
when fetching an item from cache is explained here (excerpt from https://www.apollographql.com/docs/react/caching/cache-interaction/#example-updating-the-cache-after-a-mutation):
If you call writeFragment with an options.data object that the cache is able to identify, based on its __typename and primary key fields, you can avoid passing options.id to writeFragment.
Whether you provide options.id explicitly or let writeFragment figure it out using options.data, writeFragment returns a Reference to the identified object.
This behavior makes writeFragment a good tool for obtaining a Reference to an existing object in the cache, which can come in handy when writing an update function for useMutation
This is counterintuitive as the name writeFragment
implies that it's for writing to the cache and not reading from it, but it seems to be the recommended best practice.