我正在尝试对react-apollo-hooks进行突变后实施缓存更新。
const onDeleteHandler = useMutation(DELETE_POST, {
update: (proxy, mutationResult) => {
/* custom update logic */
try {
const { deletePost } = mutationResult.data;
const postFeed = proxy.readQuery({
query: GET_POSTS, variables
})
console.log("postFeed", postFeed)
proxy.writeQuery({ query: GET_POSTS })
}
catch(error){
console.log("Cache update error", error)
}
},
})
我目前收到以下错误消息:
写入结果以供查询时出错“ kind”:“ SelectionSet”,“ selections”:[{“ kind”:“ Field”,“ name”:{“ kind”:“ Name”,“ value”:“ id”},“ arguments”:[] ,“指令”:[]},{“种类”:“字段”,“名称”:{“种类”:“名称”,“值”:“名字”},“参数”:[],“指令” :[]},{“种类”:“字段”,“名称”:{“种类”:“名称”,“值”:“姓氏”},“参数”:[],“指令”:[]} ,{“种类”:“字段”,“名称”:{“种类”:“名称”,“值”:“ __ typename”}}}}},{“种类”:“字段”,“名称”:{ “ kind”:“名称”,“值”:“ __ typename”}}]}}}}}]],“ loc”:{“开始”:0,“结束”:434}
我的直觉是writeQuery()方法需要一个如下所示的辅助变量:
proxy.writeQuery({ query: GET_POSTS, data })
但是,我不确定应该包括什么,或者甚至是问题
我的客户端查询是这样:
export const GET_POSTS = gql`
query Posts($query: String, $skip: Int, $first: Int, $orderBy: UserOrderByInput){
posts (
query: $query
skip: $skip
first: $first
orderBy: $orderBy
){
id
title
body
location
published
author {
id
firstName
lastName
}
}
}
`
和变量:
const variables = { ...queryVariables, query: value.state.searchTerm, orderBy: filter }
我写了一个小的npm软件包-apollo-offline-hooks,它简化了突变和订阅后的缓存更新。
使用它,您的代码将如下所示:
import { useMutation } from "apollo-offline-hooks";
const [deletePost] = useMutation(DELETE_POST, {
updateQuery: { query: GET_POSTS, variables }
});
const handleDelete = () => {
return deletePost({ variables: { id: POST_ID } });
};
此代码等效于下面的带有本机@apollo/react-hooks的代码
import { useMutation } from '@apollo/react-hooks';
const [deletePost] = useMutation(DELETE_POST)
const handleDelete = () => {
return deletePost({
variables: {id: POST_ID},
update: proxy => {
try {
// you need to read and write query with exactly the same variables
const cache = proxy.readQuery({ query: GET_POSTS, variables });
proxy.writeQuery({
query: GET_POSTS,
variables,
data: {
// query structure depends on your graphql schema
posts: cache.posts.filter(item => item.id !== POST_ID)
}
});
} catch (error) {
console.log(error)
}
}
})
}