Add apollo-client to a React project

Reading Time: < 1 minute

Loading

Set up Apollo Client for React

  • npm install apollo/client and graphql
npm install @apollo/client graphql
  • Create client.tsx file to store configuration of apollo-client react
  • import ApolloClient, InMemoryCache and HttpLink from ‘@apollo/client’
import { ApolloClient, InMemoryCache, HttpLink } from '@apollo/client';
  • Initialize and export an instance of ApolloClient
const uri = 'https://countries-274616.ew.r.appspot.com';
const link = new HttpLink({ uri });

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

export default client;
  • Test client instance in client.tsx by executing a GraphQL query
  • Create a new folder named graphql and add get-languages.tsx in it
  • graphql/get-languages.tsx defines a GraphQL query that returns countries where official language is English.
graphql/get-languages.tsx

import { gql } from '@apollo/client';

export const GET_LANGUAGES = gql`
    query getLanguages {
        languages: Language(
            filter: { name_in: ["English"] },   
            orderBy: [name_asc]) {
                id: _id
                name
                nativeName
                countries {
                    id: _id
                    name
                    flag {
                        emoji
                    }
                }
        }
    }
`;
  • Verify Apollo client can retrieve the results of GET_LANGUAGES and output to console
In client.tsx

import { GET_LANGUAGES } from './graphql/queries';

client.query({
  query: GET_LANGUAGES
}).then(console.log);

Connect Apollo Client to React

  • Import ApolloProvider component and client instance to App.tsx. The client instance is initialized and exported from client.tsx
  • Wrap ApolloProvider around top level element in App function
import { ApolloProvider } from "@apollo/client";
import client from './client';

const App = () => {
  return (
    <ApolloProvider client={client}>
      <React.StrictMode>
        <p>Hello World!</p>
      </React.StrictMode>
    </ApolloProvider>
  );
}

ReactDOM.render(<App/>, document.getElementById('root'));
  • Up to this point, the application can take advantage of Apollo Client to execute queries and mutations on client side