在update
useMutation 的钩子中,Apollo 的文档建议使用writeFragment
来获取对新添加对象的内部引用。我觉得这很奇怪,因为该对象已经存在于缓存中。所以我测试了它,readFragment
果然,它运行良好。在这个用例中是否有使用writeFragment
over的偏好readFragment
?
示例 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];
}
}
});
该页面的摘录:
在 cache.writeFragment 的帮助下,我们获得了对添加的 todo 的内部引用,然后将该引用存储在 ROOT_QUERY.todos 数组中。
示例 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];
}
}
});
}
});
该页面的摘录:
该评论已通过 useMutation 添加到缓存中。因此,cache.writeFragment 返回对现有对象的引用。
我还在 Apollo Client 的讨论板 ( https://github.com/apollographql/apollo-client/discussions/7515 ) 上发布了这个问题,但没有得到回复。