Multiple clients with react-apollo
November 13, 2018 at 8:42amThe Apollo community has a new home. This thread is preserved for historical purposes. The content of this conversation may be innaccurrate or out of date. Go to new community home →
Multiple clients with react-apollo
November 13, 2018 at 8:42amHey guys,
I was using 2 ApolloProviders with different clients and was calling the one I need with `use` param in graphql (HOC).
Now It's not working with 3rd ApolloProvider (example below)
<ApolloProvider client={clientOne}><ApolloProvider client={clientTwo} as="clientTwo"><ApolloProvider client={clientThree} as="clientThree"><App /></ApolloProvider></ApolloProvider></ApolloProvider>
Yeap, it's a bit stupid way, but for now because we have 3 separated endpoints we need to implement it.
One of the solution is: Put needed client in options for graphql (HOC) and it works.
1) But is there any better/elegant way to solve that ?
2) Why 1st example doesn't work with 3 clients but works with 2 ?
February 19, 2019 at 10:57am
Here is a write-up of the approach we've been taking: https://www.loudnoises.us/next-js-two-apollo-clients-two-graphql-data-sources-the-easy-way/
It should work with any number of GraphQL sources you want to include.
May 2, 2019 at 12:01pm
which solution are you referring to?
solution
, I'd recommend giving the one I suggested a try. was asking why the solution he presented didn't work. The one I linked to works great.
I am not sure of all of the details of your set up but according to this medium article Apollo Multiple Clients with React? you can actually pass a client into the Query and Mutation components to over ride which client is being used. In a case where you have maybe a main client you could pass that your ApolloProvider and then where you need to query a seperate client just pass that client into the Query component as as a prop. Or create your own <QueryWithClient1> <QueryWithClient2> <QueryWithClient3> components where you import and set the client you want so you don't have to do it manually everywhere.
const customClient = new ApolloClient({uri: "http://other-api/graphql"});const Dogs = ({ onDogSelected }) => (<Query query={GET_DOGS} client={customClient} >{({ loading, error, data }) => {if (loading) return "Loading...";if (error) return `Error! ${error.message}`;return (<select name="dog" onChange={onDogSelected}>{data.dogs.map(dog => (<option key={dog.id} value={dog.breed}>{dog.breed}</option>))}</select>);}}</Query>);
the challenge there is that you end up with multiple clients, which is contrary to many of the built in assumptions of Apollo (fairly certain on this). The solution in the post I shared keeps everything on one client, and toggles the one client's
link
attribute based on context
passed to the query. Seems cleaner.