0

I am new to graphql and react. Currently one apollo client is used by default for all useQuery and useMutation which was intialized via ApolloProvider.

Now I have to pass different apollo clients (having different uri) to different queries and mutations. I am able to pass different clients in useQuery() but not able to do the same in useMutation().

// Client initialized via ApolloProvider
const client = new ApolloClient({
    cache: new InMemoryCache(),
    link: httpLink1,
});

// Custom client with different http link
const customClient = new ApolloClient({
    cache: new InMemoryCache(),
    link: httpLink2,
});

// This is working where I can see it is using httpLink2
const { loading, error, data } = useQuery(GET_ITEMS, {
    client: customClient
});

const [myMutation] = useMutation(LOAD_ITEMS)

const loadItem (): void => {
  // not working. By default, the apollo client instance that's passed down via context is use. 
  const variables = { item: 1, client: customClient } 
  
  myMutation({ variables })
  // rest of the code
  
}

As per below useMutation() documentation I can see that we can pass different clients. https://www.apollographql.com/docs/react/data/mutations/#client. But somehow it is not working for me.

Could someone please help me here.

Thanks in advance.

iRunner
  • 1,472
  • 6
  • 25
  • 40

1 Answers1

0

You can use the same apollo client but use the httpLink conditionally. https://www.apollographql.com/docs/react/api/link/introduction#providing-to-apollo-client

Creating the link:

   import { ApolloLink, HttpLink } from '@apollo/client'; 
   const directionalLink = ApolloLink.split(
       operation => operation.getContext().clientName === "second",
       new HttpLink({ uri: "http://localhost:4000/v1/graphql" }),
       new HttpLink({ uri: "http://localhost:4000/v2/graphql" })
    ),

Initializing apollo client:

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

In the component:

const {data, error, loading} = useQuery(GET_STUFF, {
   context: { version: "second" }
});
m4china
  • 230
  • 3
  • 9