【问题标题】:I need to set my Apollo Client Cache to its defaults我需要将我的 Apollo 客户端缓存设置为默认值
【发布时间】:2019-02-24 15:22:49
【问题描述】:

我有一个使用 Apollo 客户端的 React 应用程序。我正在使用apollo-link-stateapollo-cache-persist 并且需要在我的应用程序中调用client.resetStore() 时将我的商店重置为其默认值。

文档说,在创建客户端时,您应该调用 client.onResetStore(stateLink.writeDefaults),这将完成这项工作,但 writeDefaults 由 Apollo Link State 公开,我无法直接访问,因为我正在使用 Apollo Boost。

这是我的 Apollo 客户端代码:

import ApolloClient from 'apollo-boost';
import { InMemoryCache } from 'apollo-cache-inmemory';
import { persistCache } from 'apollo-cache-persist';
import { defaults, resolvers } from "./store";

const cache = new InMemoryCache();

persistCache({
  storage: window.localStorage,
  debug: process.env.NODE_ENV !== 'production',
  cache
});

const client = new ApolloClient({
  uri: process.env.NODE_ENV === 'production' ? 'https://five-yards-api.herokuapp.com/graphql' : 'http://localhost:7777/graphql',
  credentials: 'include',
  clientState: {
    defaults,
    resolvers
  },
  cache
});

// TODO: Doesn't work as expected
client.onResetStore(client.writeDefaults);

export default client;

【问题讨论】:

    标签: reactjs apollo react-apollo apollo-client apollo-link-state


    【解决方案1】:

    AFAIK 的唯一方法是从 Apollo Boost 迁移,它为您配置了很多底层内容并手动设置 Apollo 客户端。迁移后,我可以按照文档调用onResetStore(),一切正常:)

    Apollo Boost 迁移: https://www.apollographql.com/docs/react/advanced/boost-migration.html

    【讨论】:

      【解决方案2】:

      我使用的是 Apollo Client 2.x,可能和 Apollo Boost 一样。 我对 Apollo Client 2.x 也有同样的问题,下面是我的解决方案。 在您配置 Apollo 的根文件中(例如 App.js):

      cache.writeData({data : defaultData });  # I assume you already have this to initialise your default data.
      
      # Then, you just add below underneath.
      client.onResetStore(() => {
        cache.writeData({data : defaultData });
      });
      
      const App = () => (...
      

      【讨论】:

        猜你喜欢
        • 2011-03-23
        • 2017-03-18
        • 2019-09-19
        • 2020-02-01
        • 2021-04-21
        • 2020-11-03
        • 2019-04-17
        • 1970-01-01
        相关资源
        最近更新 更多