0
votes

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

1 Answers

1
votes

Only serializable objects should be stored through redux -- functions or objects that have functions as properties do not belong in a redux store. If you need to reference the Apollo client outside of the component hierarchy of your React app, just create a module that exports the client object itself (not a function that creates a client). Then you can just import the client whereever (including the code that includes your ApolloProvider) and all your code will point at the same instance of the client (and the same cache).

It's important that the module for your client export the instantiated client itself -- if you export a function that creates the client, you'll be recreating it each time you import it.