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?
Example 1:
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.
Example 2:
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.