Get started: Set up Apollo Client in your React app
Set up Apollo Client in your React app
In this tutorial we will walk through the process of installing and configuring Apollo Client in a React application. If you're just getting started with GraphQL or the Apollo platform, I will recommend checking our first tutorial series on Apollo.
The simplest way to get started with Apollo Client in a ReactJS application is by using Apollo Boost, A starter kit that configures your client for you with our recommended settings. Apollo Boost includes packages that are essential for building an Apollo app, like in memory cache, local state management, and error handling. It's also quite flexible to handle features like authentication.
Installation
First, let's install the needed packages
npm install apollo-boost @apollo/react-hooks graphql
- apollo-boost: Package containing everything you need to set up Apollo Client
- @apollo/react-hooks: React hooks-based view layer integration
- graphql: Also parses your GraphQL queries
If you'd like to walk through this tutorial yourself, we recommend either running a new React project locally with create-react-app or creating a new React sandbox on CodeSandbox.
Create a client
Great, now that you have all the dependencies you need, let's create your Apollo Client. The only thing you need to get started is the endpoint for your GraphQL server. If you don't pass in uri directly, it defaults to the /graphql endpoint on the same host your app is served from.
In our index.js file, let's import ApolloClient from apollo-boost and add the endpoint for our GraphQL server to the uri property of the client config object.
import ApolloClient from 'apollo-boost';
const client = new ApolloClient({
uri: 'https://48p1r2roz4.sse.codesandbox.io',
});
That's it! Now your client is ready to start fetching data. Before we hook up Apollo Client to React, let's try sending a query with plain JavaScript first. In the same index.js file, try calling client.query(). Remember to first import the gql function for parsing your query string into a query document.
import { gql } from "apollo-boost";
client
.query({
query: gql`
{
rates(currency: "USD") {
currency
}
}
`
})
.then(result => console.log(result));
Open up your console and inspect the result object. You should see a data property with rates attached, along with some other properties like loading and networkStatus. While you don't need React or another front-end framework just to fetch data with Apollo Client, our view layer integrations make it easier to bind your queries to your UI and reactively update your components with data. Let's learn how to connect Apollo Client to React so we can start building query components with React Apollo.
Connect your client to React
To connect Apollo Client to React, you will need to use the ApolloProvider component exported from @apollo/react-hooks. The ApolloProvider is similar to React's Context.Provider. It wraps your React app and places the client on the context, which allows you to access it from anywhere in your component tree.
In index.js, let's wrap our React app with an ApolloProvider. We suggest putting the ApolloProvider somewhere high in your app, above any places where you need to access GraphQL data. For example, it could be outside of your root route component if you're using React Router.
import React from 'react';
import { render } from 'react-dom';
import { ApolloProvider } from '@apollo/react-hooks';
const App = () => (
<ApolloProvider client={client}>
<div>
<h2>My first Apollo app ??</h2>
</div>
</ApolloProvider>
);
render(<App />, document.getElementById('root'));
Request data
Once your ApolloProvider is hooked up, you're ready to start requesting data with the useQuery hook! useQuery is a hook exported from @apollo/react-hooks that leverages the Hooks API to share GraphQL data with your UI.
First, pass your GraphQL query wrapped in the gql function into the useQuery hook. When your component renders and the useQuery hook runs, a result object will be returned containing loading, error, and data properties. Apollo Client tracks error and loading state for you, which will be reflected in the loading and error properties. Once the result of your query comes back, it will be attached to the data property.
Let's create an ExchangeRates component in index.js to see the useQuery hook in action!
.import React from 'react';
import { useQuery } from '@apollo/react-hooks';
import { gql } from 'apollo-boost';
const EXCHANGE_RATES = gql`
{
rates(currency: "USD") {
currency
rate
}
}
`;
function ExchangeRates() {
const { loading, error, data } = useQuery(EXCHANGE_RATES);
if (loading) return <p>Loading...</p>;
if (error) return <p>Error :(</p>;
return data.rates.map(({ currency, rate }) => (
<div key={currency}>
<p>
{currency}: {rate}
</p>
</div>
));
}
Congrats, you just made your first useQuery based component! If you render your ExchangeRates component within your App component from the previous example, you'll first see a loading indicator and then data on the page once it's ready. Apollo Client automatically caches this data when it comes back from the server, so you won't see a loading indicator if you run the same query twice.
Apollo Boost
In our example app, we used Apollo Boost in order to quickly set up Apollo Client. While your GraphQL server endpoint is the only configuration option you need to get started, there are some other options we've included so you can quickly implement features like local state management, authentication, and error handling.
What's included
Apollo Boost includes some packages that we think are essential to developing with Apollo Client. Here's what's included:
- apollo-client: Where all the magic happens
- apollo-cache-inmemory: Our recommended cache
- apollo-link-http: An Apollo Link for remote data fetching
- apollo-link-error: An Apollo Link for error handling
The awesome thing about Apollo Boost is that you don't have to set any of this up yourself! Just specify a few options if you'd like to use these features and we'll take care of the rest.
Previous:
Why Apollo Client?
Next:
Queries
- New Content published on w3resource:
- Scala Programming Exercises, Practice, Solution
- Python Itertools exercises
- Python Numpy exercises
- Python GeoPy Package exercises
- Python Pandas exercises
- Python nltk exercises
- Python BeautifulSoup exercises
- Form Template
- Composer - PHP Package Manager
- PHPUnit - PHP Testing
- Laravel - PHP Framework
- Angular - JavaScript Framework
- React - JavaScript Library
- Vue - JavaScript Framework
- Jest - JavaScript Testing Framework