在delete mutation完成后,手动刷新相关查询的数据。
示例代码:
首先,在graphql代码中确保在delete mutation完成后返回被删除的对象ID。
type Mutation { deletePost(id: ID!): ID }
然后,在客户端代码中使用useMutation hook来执行delete mutation,并传递onCompleted参数来触发回调函数。
import { useMutation } from '@apollo/client'; import { DELETE_POST, GET_ALL_POSTS } from '../graphql';
const Posts = () => { const [deletePost] = useMutation(DELETE_POST, { refetchQueries: [{ query: GET_ALL_POSTS }] });
const handleDelete = (id) => {
deletePost({
variables: { id },
update(cache, { data: { deletePost } }) {
cache.modify({
fields: {
posts(existingPosts = [], { readField }) {
return existingPosts.filter(postRef => {
return deletePost !== readField('id', postRef);
});
}
}
});
}
});
}
return (
<>
{posts.map(post => (
{post.title}
))}
>
)
}
在deletePost mutation完成后,我们手动更新posts查询的缓存,删除已删除的post。这将触发posts查询重新获取数据,以便更新UI。