OpenReplay
Navigate back to the homepage
BLOG
Browse Repo
Back

Fetching Data from GraphQL APIs with Apollo React

Victoria Lo
November 8th, 2021 · 2 min read

Apollo Client is a modern and comprehensive state management library that helps developers to fetch, cache or update data from GraphQL APIs. In this article, we will take a look at how to use this library to query a GraphQL API and display its data in a React app.

Prerequisite

Before you read further, you should have at least a beginner-level of knowledge in GraphQL. If not, please check out my GraphQL for Beginner Series.

Introduction to Apollo React

Apollo React has a declarative data fetching approach that gives the code predictability and efficiency. There is no need to manually track loading states with Apollo React.

It is also fully compatible with any GraphQL API and setup, allowing it to be easily integrated with such apps. Specifically, it is very powerful with React apps as it features built-in support and React Hooks.

For more information on Apollo Client, feel free to read its documentation.

Step 1: Getting Started

In this example, I will be using the Pokémon GraphQL API to fetch and display data in my app.

Let’s get started by installing Apollo Client and GraphQL packages in a React App:

1npm install @apollo/client graphql

Step 2: Initialize ApolloClient

In our index.js, let us initialize an ApolloClient instance by importing the following:

1import {
2 ApolloClient,
3 InMemoryCache,
4 ApolloProvider
5} from "@apollo/client";

Below the import statement, we initialize the instance like so:

1const client = new ApolloClient({
2 uri: 'https://beta.pokeapi.co/graphql/v1beta',
3 cache: new InMemoryCache()
4});

The uri refers to the endpoint of the GraphQL API. As shown in the screenshot below, our PokeAPI is located at: https://beta.pokeapi.co/graphql/v1beta

image.png

Finally, we wrap the ApolloProvider component around our App component, passing client as a prop.

1ReactDOM.render(
2 <ApolloProvider client={client}>
3 <React.StrictMode>
4 <App />
5 </React.StrictMode>
6 </ApolloProvider>,
7 document.getElementById('root')
8);

Step 3: Write the Query

In the React’s app src folder, let’s create a gql folder. This is where we will write all our queries or mutation. It keeps the code organized.

Inside the gql folder, create a file called Query.js, where we will write our query to fetch data from the PokeAPI.

At this point, the app structure should roughly look like this:

image.png

In gql/Query.js, we will first import gql, then export and write our GraphQL query inside it like so:

1import { gql } from "@apollo/client";
2
3export const GET_GEN_3 = gql`
4 query getGen3 {
5 pokemon_v2_pokemonspecies(
6 order_by: { id: asc }
7 where: { pokemon_v2_generation: { name: { _eq: "generation-iii" } } }
8 ) {
9 name
10 id
11 }
12 }
13`;

In this example, we are querying all Pokémon’s name and id that were from Generation 3 aka Hoenn region (i.e. created in 2003).

Step 4: Run the Query

To execute the query, head over to App.js. Import the useQuery Hook and the query:

1import { useQuery } from '@apollo/client';
2import { GET_GEN_3 } from "./gql/Query";

Then, run the query with this one line:

1function App() {
2 const { loading, error, data } = useQuery(GET_GEN_3);
3 console.log(data);
4 //...
5}

Now, we can run npm start and we should see our Pokémon data has been successfully fetched in the following format:

image.png

Step 5: Display Data in React

Our next step is to display this fetched data in our App.

In the return function of App.js, we can simply use conditionals and map the data like this:

1return (
2 <div className="App">
3 <header className="App-header">
4 {loading ? (
5 <img src={logo} className="App-logo" alt="logo" />
6 ) : error ? (
7 <p>Error: {error}</p>
8 ) : (
9 <div>
10 {data.pokemon_v2_pokemonspecies.map((pokemon) => {
11 return (
12 <p>
13 {pokemon.id} {pokemon.name}
14 </p>
15 );
16 })}
17 </div>
18 )}
19 </header>
20 </div>
21 );

In the code above, we show different UI based on the state of the query. If it is loading, we will show a loading animation. Else if there’s an error, we simply print it on the app. Else, we shall map the pokemon_v2_pokemonspecies array and print each Pokemon’s name and id.

Open Source Session Replay

Debugging a web application in production may be challenging and time-consuming. OpenReplay is an Open-source alternative to FullStory, LogRocket and Hotjar. It allows you to monitor and replay everything your users do and shows how your app behaves for every issue. It’s like having your browser’s inspector open while looking over your user’s shoulder. OpenReplay is the only open-source alternative currently available.

OpenReplay

Happy debugging, for modern frontend teams - Start monitoring your web app for free.

Result

Here is the result of our very simple example. load.gif

Conclusion

Thanks for reading. I hope this article has helped you in getting started with Apollo Client. Note that Apollo Client automatically caches queries and therefore, subsequent executions of the same query will be very fast.

Apollo Client also supports other GraphQL operations such as Mutations, Subscriptions and more. Do read their documentation to learn more. Cheers!

More articles from OpenReplay Blog

Integrating OpenReplay with GitHub

Generate Github issues directly from the OpenReplay interface

November 5th, 2021 · 3 min read

Beginner’s Guide to SWR: Data Fetching in React

Learn about SWR and what it means for your HTTP-needs

October 27th, 2021 · 3 min read
© 2021 OpenReplay Blog
Link to $https://twitter.com/OpenReplayHQLink to $https://github.com/openreplay/openreplayLink to $https://www.linkedin.com/company/18257552