Deleting Apollo Client cache for a given query and every set of variables

时间:2018-02-03 10:21:41

标签: graphql react-apollo apollo-client

I have a filtered list of items based on a getAllItems query, which takes a filter and an order by option as arguments.

After creating a new item, I want to delete the cache for this query, no matter what variables were passed. I don't know how to do this.

I don't think updating the cache is an option. Methods mentionned in Apollo Client documentation (Updating the cache after a mutation, refetchQueries and update) all seem to need a given set of variables, but since the filter is a complex object (with some text information), I would need to update the cache for every given set of variables that were previously submitted. I don't know how to do this. Plus, only the server does know how this new item impact pagination and ordering.

I don't think fetch-policy (for instance setting it to cache-and-network) is what I'm looking for, because if accessing the network is what I want after having created a new item, when I'm just filtering the list (typing in a string to search), I want to stay with the default behavior (cache-only).

client.resetStore would reset the store for all type of queries (not only the getAllItems query), so I don't think it's what I'm looking for either.

I'm pretty sure I'm missing something here.

3 个答案:

答案 0 :(得分:3)

当前版本的Apollo中没有官方支持的方法来执行此操作,但是有一种解决方法。

在更新功能中,创建项目后,您可以遍历缓存并删除键以您要从缓存中删除的类型名开头的所有节点。例如

// Loop through all the data in our cache
// And delete any items where the key start with "Item"
// This empties the cache of all of our items and 
// forces a refetch of the data only when it is next requested.
Object.keys(cache.data.data).forEach(key => 
  key.match(/^Item/) && cache.data.delete(key)
)

这适用于在缓存中多次存在且具有不同变量的查询,即分页查询。

我写了一篇有关Medium的文章,详细介绍了它是如何工作的,以及一个实现示例和替代解决方案,该示例和替代解决方案更复杂,但在少数用例中效果更好。由于本文详细介绍了我已经在此答案中解释过的概念,因此我相信可以在此处分享:https://medium.com/@martinseanhunt/how-to-invalidate-cached-data-in-apollo-and-handle-updating-paginated-queries-379e4b9e4698

答案 1 :(得分:0)

ngrx喜欢

print()

答案 2 :(得分:0)

这对我有用(需要apollo 2具有缓存逐出功能)-从缓存中清除与正则表达式匹配的查询

清除缓存查询后,将自动重新设置缓存查询,而无需手动触发refetch(如果您使用angular:gql.watch()。valueChanges将执行xhr请求并发出新值)

export const deleteQueryFromCache = (cache: any, matcher: string | RegExp): void => {
    const rootQuery = cache.data.data.ROOT_QUERY;
    Object.keys(rootQuery).forEach(key => {
        if (key.match(matcher)) {
            cache.evict({ id: "ROOT_QUERY", fieldName: key })
        }
    });
}