您可以在ApolloClient的客户端解析器中而不是“ cache”中访问“ client”吗?

时间:2019-07-08 12:57:36

标签: reactjs graphql apollo-client

是否可以从ApolloClient解析器而不是client访问cache

我正试图编写一个解析器,当单击按钮(本质上是注销)时,它会清除localStorage和缓存,但不知道如何访问客户端。

我完全可以访问缓存,但是尽管有官方文档,但我发现cache.resetStore()不是控制台(或cache.clearStore() if I use that function)中的函数错误。

运行ApolloClient,React和apollo-link-state,并使用compose将组件封装在graphql() HOC中。

resolvers.js

  Mutation: {
    logout: (_, __, { cache }) => {
      localStorage.clear();
      cache.writeData({
        data: {
          AuthData: {
            __typename: 'AuthData',
            token: null,
            currentUserId: null,
            expirationTime: null
          }
        }
      });
    }
  }
};

index.js

import ReactDOM from 'react-dom';
import App from './App';
import { BrowserRouter } from 'react-router-dom';

//Apollo
import { ApolloProvider } from 'react-apollo';
import { ApolloClient } from 'apollo-client';
import { ApolloLink } from 'apollo-link';
import { createHttpLink } from 'apollo-link-http';
import { InMemoryCache } from 'apollo-cache-inmemory';
import { withClientState } from 'apollo-link-state';
import { resolvers } from './resolvers';

const cache = new InMemoryCache();

...
...

const initialState = {
  AuthData: {
    __typename: 'AuthData',
    token: localStorage.getItem('token') || null,
    currentUserId: localStorage.getItem('currentUserId') || null,
    expirationTime: localStorage.getItem('expirationTime') || null
  },
  ErrorLog: {
    __typename: 'ErrorLog',
    errors: []
  }
};

const stateLink = withClientState({
  cache,
  defaults: initialState,
  resolvers
});

const link = ApolloLink.from([stateLink, httpLink]);

const client = new ApolloClient({
  link,
  cache
});

预期:

  • 要清除所有数据的客户端缓存。

实际:

  • 获取错误client is not definedcache.resetStore()不是函数。

0 个答案:

没有答案