Apollo-client: How to use apollo client without/outside component?

Created on 7 Jul 2020  路  5Comments  路  Source: apollographql/apollo-client

I have to use apollo client without react component , it means that I cannot use useApolloClient hook and withApollo HOC. I wanna use client.query and client.mutate methods, so I have to be able to access client instance. In this situation, I extracted client instance as separate module and import that instance. Is it right way to use apollo client outside component? If it isn't, what is the best approach?

client.ts (NOT REACT COMPONET)

export const client = new ApolloClient(...)

outsideComponent.ts (NOT REACT COMPONET)

import { client } from './client';

const veryComplexQuery = client.query....

All 5 comments

See the section regarding using Apollo Client without React from the Migrate to Apollo v3 docs.

In short

import { ApolloClient } from '@apollo/client/core';

Edit:
The API docs have not been updated for v3 yet but in the example here, all the imports should now be imported from @apollo/client/core.

import {
  InMemoryCache,
  HttpLink,
  ApolloClient
} from '@apollo/client/core';

@jonathonadams Thanks for the answer, but you misunderstood my question. My question was that how can I use client instance outside component? NOT ApolloClient constructor/class. Anyway, it is solved by DI(Dependency Injection). Thank you.

Hey @baeharam , do you mind providing an example of how you solved this with dependency injection? Are you referring to your initial explanation of creating the client instance in a separate module and then just importing it where you need it? Have you ran into any issues with that config? Thx for your time!

@baeharam Could you share your solution?

This is what I have done. I am using a singleton pattern.

let apolloClient: ApolloClient<NormalizedCacheObject> | undefined;

export const getApolloClient = () => {
  if (apolloClient) {
    return apolloClient;
  }
 // -- code to configure client is redacted -- 
  apolloClient = new ApolloClient({
    // ...
    // various options
  });

  return apolloClient;
};

Now, wherever I need client, I call getApolloClient().

Was this page helpful?
0 / 5 - 0 ratings