【问题标题】:Reset cache by especific query or mutation通过特定查询或突变重置缓存
【发布时间】:2018-12-31 07:32:24
【问题描述】:

我想使用 react-apollo 的客户端从键或查询中重置部分缓存,而不是使用 client.resetStore() 清除整个缓存。

例子:

import { withApollo } from "react-apollo";
import { compose } from "recompose";
import MyComponent from "./MyComponent";

const cleanEspecificCache = ({ client }) => () =>{
  // What i do here?
}

const enhance = compose(
 withApollo,
 withHandlers({cleanEspecificCache})
)

export default enhance(MyComponent);

我怎么做才能让它工作?谢谢!

【问题讨论】:

    标签: javascript react-native caching graphql react-apollo


    【解决方案1】:

    根据此问题,目前不支持部分 Apollo 缓存清除: https://github.com/apollographql/apollo-feature-requests/issues/4

    您可以使用fechPolicy: 'network-only' 根本不缓存特定查询:

    const enhance = compose(
      graphql(
        gql`{
          food {
            id
            name
          }
        }`,
        {
          options: { fetchPolicy: 'network-only' },
        }
      ),
      ...
    );
    
    export default enhance(MyComponent);
    

    如果您想深入兔子洞并立即找到解决方案,可以尝试https://github.com/sysgears/apollo-cache-router 它可以将您的缓存拆分为两个或更多缓存,然后您可以单独重置这些缓存:

    import { InMemoryCache } from 'apollo-cache-inmemory';
    import ApolloCacheRouter from 'apollo-cache-router';
    import { hasDirectives } from 'apollo-utilities';
    
    const generalCache = new InMemoryCache();
    const specialCache = new InMemoryCache();
    const cache = ApolloCacheRouter.override(
      ApolloCacheRouter.route([generalCache, specialCache], document => {
        if (hasDirectives(['special'], document)) {
          // Pass all queries marked with @special into specialCache
          return [specialCache];
        } else {
          // Pass all the other queries to generalCache
          return [generalCache];
        }
      })
    );
    

    并且每当您想在代码中重置 specialCache 调用 specialCache.reset()

    【讨论】:

      猜你喜欢
      • 2021-01-14
      • 2012-12-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-01
      • 2020-05-08
      • 2020-03-26
      • 1970-01-01
      • 2023-03-03
      相关资源
      最近更新 更多