ApolloClient:从所有查询的缓存中删除项目?
ApolloClient: Delete item from cache across all queries?
当涉及到 ApolloClient 缓存时,我熟悉执行更新和插入的各种方法,但这个问题是关于删除的。
假设用户选择删除“id”为 123 的“note”项。我希望在缓存中完全删除“note:123”。有办法吗?
例如,在进行更新时,我经常使用 writeFragment
来更新特定的注释,这符合我的预期,在所有查询中更新该注释。但是,我注意到明显缺少 deleteFragment
方法。我错过了什么吗?
看起来 ApolloClient v3 允许您为此使用 evict()。据我所知,这是删除项目的唯一方法,无需知道它出现在下面的查询和变量的每个组合。
您可以 update
选项在变更后更新您的缓存。试试这个:
const DELETE_ITEM = gql`
DeleteItem($id: ID!) {
deleteItem(id: $id) {
...
}
}
`
const LIST_ITEMS = gql`
ListItem($query: ListItemInput!) {
listItem(query: $query) {
items {
id
}
}
}
`
const [deleteItem] = useMutation(DELETE_ITEM, {
update: (cache, { deleteItem }) => {
const { listItem } = cache.readQuery(LIST_ITEMS, {
variables: {
query: {...}
}
})
const index = listItem.items.findIndex(
item => item.id === deleteMessage.id
)
if (index > -1) {
listItem.items.splice(index, 1)
cache.writeQuery({
query: LIST_ITEMS,
{
variables: {
query: {...}
}
},
data: {
listItem,
},
})
}
}
})
当涉及到 ApolloClient 缓存时,我熟悉执行更新和插入的各种方法,但这个问题是关于删除的。
假设用户选择删除“id”为 123 的“note”项。我希望在缓存中完全删除“note:123”。有办法吗?
例如,在进行更新时,我经常使用 writeFragment
来更新特定的注释,这符合我的预期,在所有查询中更新该注释。但是,我注意到明显缺少 deleteFragment
方法。我错过了什么吗?
看起来 ApolloClient v3 允许您为此使用 evict()。据我所知,这是删除项目的唯一方法,无需知道它出现在下面的查询和变量的每个组合。
您可以 update
选项在变更后更新您的缓存。试试这个:
const DELETE_ITEM = gql`
DeleteItem($id: ID!) {
deleteItem(id: $id) {
...
}
}
`
const LIST_ITEMS = gql`
ListItem($query: ListItemInput!) {
listItem(query: $query) {
items {
id
}
}
}
`
const [deleteItem] = useMutation(DELETE_ITEM, {
update: (cache, { deleteItem }) => {
const { listItem } = cache.readQuery(LIST_ITEMS, {
variables: {
query: {...}
}
})
const index = listItem.items.findIndex(
item => item.id === deleteMessage.id
)
if (index > -1) {
listItem.items.splice(index, 1)
cache.writeQuery({
query: LIST_ITEMS,
{
variables: {
query: {...}
}
},
data: {
listItem,
},
})
}
}
})