Access application wide client when using Redux?

时间:2018-10-02 09:14:48

标签: redux react-redux apollo react-apollo

I'm using Redux to manage state and Apollo to execute graphQL queries.

I create an Apollo client that should be accessible from various React components.

import { ApolloClient } from 'apollo-client';
import { HttpLink } from 'apollo-link-http';
import { InMemoryCache } from 'apollo-cache-inmemory';

const link = new HttpLink({
    uri: getGraphqlEndpointUrl,
    headers: {
        'x-api-key': getApiKey(),
        'Authorization': jwtToken,
    },
});
const client = new ApolloClient({
    link: link,
    cache: new InMemoryCache(),
});

How do I do this with Redux? Do I store the client in a variable in the Redux store? That seems a bit strange to me, but not unreasonable. Is there a better way though?

1 个答案:

答案 0 :(得分:1)

仅可序列化对象应通过redux存储-函数或具有属性的对象不属于redux存储。如果您需要在React应用程序的组件层次结构之外引用Apollo客户端,只需创建一个模块即可导出客户端对象本身(不是一个创建客户端的函数)。然后,您可以随时随地导入客户端(包括包含ApolloProvider的代码),并且所有代码都将指向客户端的相同实例(和相同的缓存)。

客户端模块导出实例化客户端本身很重要-如果您导出创建客户端的函数,则每次导入时都会重新创建该客户端。