Reactjs Apollo客户端从缓存中删除项
为什么我在用阿波罗的客户机。我用许多不同的变量查询帖子。所以我在不同的“缓存”中有一个帖子。现在我想删除一篇帖子。所以我需要从所有的“缓存”中删除这个特定的帖子 查询后:Reactjs Apollo客户端从缓存中删除项,reactjs,apollo-client,Reactjs,Apollo Client,为什么我在用阿波罗的客户机。我用许多不同的变量查询帖子。所以我在不同的“缓存”中有一个帖子。现在我想删除一篇帖子。所以我需要从所有的“缓存”中删除这个特定的帖子 查询后: export const POSTS = gql` query posts( $after: String $orderBy: PostOrderByInput $tags: JSONObject $search: String $orde
export const POSTS = gql`
query posts(
$after: String
$orderBy: PostOrderByInput
$tags: JSONObject
$search: String
$orderByTime: Int
) {
posts(
after: $after
orderBy: $orderBy
tags: $tags
search: $search
orderByTime: $orderByTime
) {
id
title
...
}
}
`;
我尝试了cache.modify(),它在我的代码中没有定义([https://www.apollographql.com/docs/react/caching/cache-interaction/#cachemodify][1] )
我还使用了useAppolloClient()以获得相同的结果
THX以获取任何帮助。您可以将更新程序传递到
use
或deletePost
。使用deletePost
应该更容易,因为它可能知道要删除的内容:
deletePost({
variables: { idToRemove },
update(cache) {
cache.modify({
fields: {
posts(existingPosts = []) {
return existingPosts.filter(
postRef => idToRemove !== readField('id', postRef)
);
},
},
});
},
});
您应该更改
变量
,以匹配您的变异。这应该是可行的,因为posts
位于查询的顶层。对于更深的字段,您需要一种获取父对象id的方法readQuery
或顶部的一系列readField
可能会对您有所帮助。此选项对我有效
const GET_TASKS = gql`
query tasks($listID: String!) {
tasks(listID: $listID) {
_id
title
sort
}
}
`;
const REMOVE_TASK = gql`
mutation removeTask($_id: String) {
removeTask(_id: $_id) {
_id
}
}
`;
const Tasks = () => {
const { loading, error, data } = useQuery(GET_TASKS, {
variables: { listID: '1' },
});
сonst [removeTask] = useMutation(REMOVE_TASK);
const handleRemoveItem = _id => {
removeTask({
variables: { _id },
update(cache) {
cache.modify({
fields: {
tasks(existingTaskRefs, { readField }) {
return existingTaskRefs.filter(
taskRef => _id !== readField('_id', taskRef),
);
},
},
});
},
});
};
return (...);
};
您可以使用
cache.execute
,而不是使用cache.modify
,这会使代码更短:
deletePost({
variables: { id },
update(cache) {
const normalizedId = cache.identify({ id, __typename: 'Post' });
cache.evict({ id: normalizedId });
cache.gc();
}
});
const GET_TASKS = gql`
query tasks($listID: String!) {
tasks(listID: $listID) {
_id
title
sort
}
}
`;
const REMOVE_TASK = gql`
mutation removeTask($_id: String) {
removeTask(_id: $_id) {
_id
}
}
`;
const Tasks = () => {
const { loading, error, data } = useQuery(GET_TASKS, {
variables: { listID: '1' },
});
сonst [removeTask] = useMutation(REMOVE_TASK);
const handleRemoveItem = _id => {
removeTask({
variables: { _id },
update(cache) {
cache.modify({
fields: {
tasks(existingTaskRefs, { readField }) {
return existingTaskRefs.filter(
taskRef => _id !== readField('_id', taskRef),
);
},
},
});
},
});
};
return (...);
};
deletePost({
variables: { id },
update(cache) {
const normalizedId = cache.identify({ id, __typename: 'Post' });
cache.evict({ id: normalizedId });
cache.gc();
}
});