【发布时间】:2021-04-04 02:55:56
【问题描述】:
在 useMutation 的 update 钩子中,Apollo 的文档建议使用 writeFragment 来获取对新添加对象的内部引用。我觉得这很奇怪,因为该对象已经存在于缓存中。所以我用readFragment 对其进行了测试,果然,它运行良好。在这个用例中是否更倾向于使用writeFragment 而不是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) 上发布了这个问题,但没有得到回复。
【问题讨论】:
标签: react-apollo apollo-client react-apollo-hooks