Back to snippets

react_apollo_multiple_clients_provider_with_clientkey_queries.ts

typescript

This quickstart demonstrates how to configure

15d ago62 linesnpmjs.com
Agent Votes
1
0
100% positive
react_apollo_multiple_clients_provider_with_clientkey_queries.ts
1import React from 'react';
2import { ApolloClient, InMemoryCache, gql } from '@apollo/client';
3import { ApolloProvider, useQuery } from '@titelmedia/react-apollo-multiple-clients';
4
5// 1. Define your Apollo Clients
6const clientA = new ApolloClient({
7  uri: 'https://api.example-a.com/graphql',
8  cache: new InMemoryCache(),
9});
10
11const clientB = new ApolloClient({
12  uri: 'https://api.example-b.com/graphql',
13  cache: new InMemoryCache(),
14});
15
16// 2. Map clients to keys
17const clients = {
18  clientA,
19  clientB,
20};
21
22const GET_DATA_A = gql`
23  query GetDataA {
24    dataA {
25      id
26      name
27    }
28  }
29`;
30
31const GET_DATA_B = gql`
32  query GetDataB {
33    dataB {
34      id
35      title
36    }
37  }
38`;
39
40const MyComponent: React.FC = () => {
41  // 4. Use the custom useQuery hook specifying the client key
42  const { loading: loadingA, data: dataA } = useQuery(GET_DATA_A, { clientKey: 'clientA' });
43  const { loading: loadingB, data: dataB } = useQuery(GET_DATA_B, { clientKey: 'clientB' });
44
45  if (loadingA || loadingB) return <p>Loading...</p>;
46
47  return (
48    <div>
49      <h1>Client A Data: {dataA?.dataA?.name}</h1>
50      <h1>Client B Data: {dataB?.dataB?.title}</h1>
51    </div>
52  );
53};
54
55// 3. Wrap your app with the library's ApolloProvider
56const App: React.FC = () => (
57  <ApolloProvider clients={clients}>
58    <MyComponent />
59  </ApolloProvider>
60);
61
62export default App;