微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何在 ApolloClient v3 中删除单个缓存

如何解决如何在 ApolloClient v3 中删除单个缓存

我已经使用了 24 小时,但似乎没有任何效果..... 正确。我看过的文档:

  1. How to invalidate cached data in Apollo and handle updating paginated queries
  2. Not sure what this does

我有一个搜索栏,可以查询我的 GraphQL (GQ) 服务器。单击时,下拉列表会显示最近的搜索。当它打开时,GQ 被获取。为了简单起见,我将只关注概念:

  1. 当我删除最近的搜索时,匹配的缓存搜索查询也应该被删除删除了什么?数据库中的相关缓存和数据。
// RecentSearches component

import { GetRecentSearches,DeleteRecentSearchDetails,QuerySearches } from '../somewhere';

// Mutation function
const [deleteRecentSearch] = useMutation(DeleteRecentSearchDetails);

// Query
const { loading,data,refetch,networkStatus } = useQuery(GetRecentSearches,{
  notifyOnNetworkStatusChange: true
});

这是我遇到问题的地方。单击 deleteRecentSeach 后,我应该能够删除最近搜索的缓存查询。如果我不这样做,重新输入相同的查询将不会获取,因为缓存已经在浏览器中,所以我必须先删除它。

deleteRecentSearch({
  variables: { id },update: async (cache,payload) => {
    const queryKey = localStorage.getItem('queryKey');
    const queryVars = { query: queryKey }

    const prevQuery = cache.readQuery({ 
      query: QuerySearches,variables: queryVars 
    })
     
    // This is what I want to remove:
    console.log(prevQuery)

    // Based on the linked Medium post,// I thought this was it but I guess not.
    await cache.writeQuery({
      query: QuerySearches,data: { query: null },variables: queryVars
    })

    // I thought it was easy as:
    // delete prevQuery.query ? but nope.

    // This does nothing. The id on "query" is queryKey (ie: 'london')
    cache.modify({
      id: cache.identify(queryKey),broadcast: false,fields: {
      query(_,{ DELETE }) {
          return DELETE;
        },},})

    // For the RecentSearch,this works:
    cache.modify({
      fields: {
        recentSearches: (searches,{ readField }) => {
          return searches.filter(
            ref => id !== readField('id',ref),);
        },})
    
  }
}).then( _ => refetch());

如果我可以删除 prevQuery,我的问题就会解决。有什么想法吗?

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。