Fetching GraphQL Data with React as a UI Library

Step 1: Create an open-source application

npx create-react-app graphql

Step 2: Move into the project folder

cd graphql

Step 3: The project Structure will look like

Step 4: Let’s modify App.js component to include ApolloClient and ApolloProvider

In the App.js component, we will use the ApolloProvider to utilise the GraphQL queries in our react app. We will wrap the entire application inside an ApolloProvider component, and give it an ApolloClient with a graphQL API pointing to a Pokemon API, which we will eventually use to fetch the list of the pokemons and display the same on the web page.

We will create a new ApolloClient like below

Javascript




const client = new ApolloClient({
  uri: 'https://graphql-pokeapi.graphcdn.app/'
  cache: new InMemoryCache(),
});


We will wrap the entire App.js in the ApolloProvider like below –

Wrapping the entire App component inside the ApolloProvider ensures all the child components, or rather, the entire App components, to use the GraphQL API seamlessly. Because of this, we will be able to call the GraphQL API endpoint inside the App component.

Javascript




function ApolloApp() {
  return (
    <ApolloProvider client={client}>
      <App />
    </ApolloProvider>
  );
}


We will use the below GraphQL query to fetch the list of all the pokemons, with a total limit of upto 10. In the below query, we specify that we want to get the list of pokemons, and that the individual pokemon data in the list should only contain the id, name, and image, and the list as a whole should only return the total count, next, previous, status, and message.

const GET_POKEMONS = gql`
query getPokemons {
pokemons(limit: 10, offset: 0) {
count
next
previous
status
message
results {
id
name
image
}
}
}
`;

Now, we will use the above query to fetch the list and display the same in the App component –

In the below code, we use the useQuery hook, provided by the ApolloClient, to get the loading state, error, and data values from the GET_POKEMONS GraphQL query. We will then loop over the pokemon data, present in the data object, and display the pokemon’s names in the form of a list in the UI.

Javascript




function App() {
  const { loading, error, data } = useQuery(GET_POKEMONS);
  
  if (loading) return <p>Loading...</p>;
  if (error) return <p>Error: {error.message}</p>;
  
  return (
    <div>
      <h1>Pokemons</h1>
      <ul>
        {data?.pokemons?.results?.map(pokemon => (
          <li key={pokemon.id}>
            {pokemon.name}
          </li>
        ))}
      </ul>
    </div>
  );
}


Our final App.js component will look like below

Javascript




import React from 'react';
import { ApolloProvider, useQuery, gql } from '@apollo/client';
import { ApolloClient, InMemoryCache } from '@apollo/client';
  
const client = new ApolloClient({
  uri: 'https://graphql-pokeapi.graphcdn.app/'
  cache: new InMemoryCache(),
});
  
const GET_POKEMONS = gql`
  query getPokemons {
    pokemons(limit: 10, offset: 0) {
      count
      next
      previous
      status
      message
      results {
        id
        name
        image
      }
    }
  }
`;
  
function App() {
  const { loading, error, data } = useQuery(GET_POKEMONS);
  
  if (loading) return <p>Loading...</p>;
  if (error) return <p>Error: {error.message}</p>;
  
  return (
    <div>
      <h1>Pokemons</h1>
      <ul>
        {data?.pokemons?.results?.map(pokemon => (
          <li key={pokemon.id}>
            {pokemon.name}
          </li>
        ))}
      </ul>
    </div>
  );
}
  
function ApolloApp() {
  return (
    <ApolloProvider client={client}>
      <App />
    </ApolloProvider>
  );
}
  
export default ApolloApp;


Output:

The output for the above code will look like below

Data Fetching with GraphQL

GraphQL is an open-source technology that allows us to query only the data that we require, unlike the traditional REST architecture which returns us the entire resources and data with specific endpoints configured for the same. Using GraphQL, we specify using the query the data that we want, and it returns the specified data in the specified format. It helps reduce the amount of data transfer over the network and saves network bandwidth.

This article will teach us how to fetch data using GraphQL, with React as our front-end UI library.

Similar Reads

Fetching GraphQL Data with React as a UI Library

Step 1: Create an open-source application...

Fetching GraphQL Data Using Fetch API

...

Fetching Data with GraphiQL

...

Conclusion

...

Contact Us