Setting Up Apollo Client with React
Apollo Client is a tool used to send and receive data to and from a GraphQL API. It is usually best to use Apollo Server with Apollo Client, though it is not a requirement.
Setting up React
Before setting up Apollo Client, we first need to create our React project. To do this, we are simply going to use create-react-app. First install Create React App if you have not already done so, by typing the following shell command in your project folder:
npm install create-react-appNext, initialise an app for this tutorial:
npx create-react-app apollo-client-tutorial
Change into the created folder:
cd apollo-client-tutorial
We can now install the Apollo Client package:
npm i @apollo/client
Setting up Apollo Client
To use Apollo Client, we must first set up our Apollo Client provider.
To do this, we need to go into our index.js file in our src directory which should look something like this:
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById('root')
);
reportWebVitals();
Import the following packages from @apollo/client:
import {
ApolloClient,
ApolloProvider,
InMemoryCache
} from '@apollo/client'
We will then be able to create our Apollo Client that will be used by our provider using the following code:
const client = new ApolloClient({
cache: new InMemoryCache(),
uri: 'http://localhost:4000/graphql'
})
Remember to replace the uri to the location of your GraphQL server.
The next step is to remove React.StrictMode and webVitals and then to wrap our Apollo Provider around the app with the client prop set to ApolloClient. Our index.js file should then look like this:
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import {
ApolloClient,
ApolloProvider,
InMemoryCache
} from '@apollo/client'
const client = new ApolloClient({
cache: new InMemoryCache(),
uri: 'http://localhost:4000/graphql'
})
ReactDOM.render(
<ApolloProvider client={client}>
<App />
</ApolloProvider>,
document.getElementById('root')
);
Apollo Client should now work throughout your React application, meaning you can now use useQuery, useMutation and other Apollo Client hooks in your App component or any components underneath the App component.