DEV Community

Cover image for Creating an App with React, Apollo, and GraphQL: A Step-by-Step Guide to Fetching Data and Error Handling
Beatrice Egumandi
Beatrice Egumandi

Posted on

Creating an App with React, Apollo, and GraphQL: A Step-by-Step Guide to Fetching Data and Error Handling

Are you looking to build a modern web application with scalable, data-driven user interfaces? Then this article is for you. In this step-by-step guide, I'll walk you through the steps required to fetch data from a GraphQL endpoint using Apollo Client in a React application, and how to handle errors that may occur during the process.

Introduction

In case you are not familiar with the terms:

  • GraphQL is a powerful query language for APIs (Application Programming Interface) that was developed by Facebook. It provides a more efficient, powerful, and flexible alternative to REST APIs (Representational State Transfer Application Programming Interface) for building modern web applications. With GraphQL, instead of requesting pre-defined data structures from a server, clients can specify exactly what data they need and receive a JSON (JavaScript Object Notation) object that matches their request. This means that you can retrieve only the data you need, reducing the amount of network traffic and improving performance. See Documentation

  • Apollo Client is a JavaScript library that provides a way to interact with a GraphQL API from a client-side application. It allows you to fetch data from a GraphQL server, cache it locally, and manage its state in your application. It provides a simple and flexible way to query and mutate data using GraphQL, making it easy to build powerful, data-driven user interfaces. See Documentation

Prerequisites
You'll need to have some basic knowledge of React and JavaScript.

Setting up the Environment

Before we get started, let's make sure we have the necessary tools and libraries installed. We'll be using create-react-app to create a new React project, and Apollo Client to query our GraphQL endpoint.

npx create-react-app my-app
cd my-app
npm install @apollo/client graphql
Enter fullscreen mode Exit fullscreen mode

Defining the GraphQL Endpoint

To fetch data from a GraphQL API, we need to define the endpoint that we'll be making requests to. For this example, we'll use the following endpoint:

https://countries.trevorblades.com/graphql
Enter fullscreen mode Exit fullscreen mode

Setting up Apollo Client

Next, we'll set up Apollo Client in our index.js file and wrap our App component with the Apollo Provider. Our index.js file should look like this:

import { ApolloClient, InMemoryCache, ApolloProvider } from '@apollo/client';

const client = new ApolloClient({
  uri: 'https://countries.trevorblades.com/graphql',
  cache: new InMemoryCache(),
});

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <React.StrictMode>
    <ApolloProvider client={client}>
      <App />
    </ApolloProvider>
  </React.StrictMode>
);
Enter fullscreen mode Exit fullscreen mode

This code creates a new instance of ApolloClient, and sets the URI to our GraphQL endpoint. It wraps our App in the ApolloProvider passing client object as a prop. You might be wondering why "uri" (Uniform Resource Identifier) and not "url"(Uniform Resource Locator) and that's because in the context of Apollo Client, "uri" refers to the location of the GraphQL server that the client will connect to in order to fetch data. This is likely because the URI includes not only the location of the server, but also additional details such as the protocol and any query parameters, while a URL refers specifically to the location of a resource.

Creating a Query Component

Now that we have our GraphQL endpoint and Apollo Client set up, we can now fetch data from the API. In our App.js file paste in the following code:

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

const GET_LOCATIONS = gql`
  query GetLocations {
    country(code: "BR") { //Add your query here
      name
      native
      capital
      emoji
      currency
      languages {
        code
        name
      }
    }
  }
`;

const App = () => {
 const { loading, error, data } = useQuery(GET_LOCATIONS);
 const {name, currency, capital, native, emoji, languages} = data?.country || {};

 if (loading) return <p>Loading...</p>;
 if (error) return <p>Error: {error.message}</p>;

return (
 <div key={name}>
      <h2>Let's Know Our Countries 🚀</h2>
      <h3>Country: {name}</h3>
      <br />
      <b>About this location:</b>
      <ol>
        <li>Capital is known as {capital}</li>
        <li>Its symbol is {emoji}</li>
        <li>Its native is {native}</li>
        <li>Currency: {currency}</li> 
        {languages?.map((lang) => (
          <ol key={lang.code}>
            <li>Language: {lang.name}</li>
            <li>Code: {lang.code}</li>
          </ol>
        ))}
      </ol>
 </div>
);

export default App;
Enter fullscreen mode Exit fullscreen mode

This code uses the useQuery hook from Apollo Client to take a GraphQL query as its argument and return an object that contains the data, loading, and error states for that query. In this case, the query is defined using the gql template literal function and assigned to a variable called GET_LOCATIONS.
The App component then calls useQuery with GET_LOCATIONS as its argument, and destructures the resulting loading, error, and data states. The data state is destructured further to get the name, currency, capital, native, emoji, and languages fields from the GraphQL response. It also handles loading and error states and returns the UI to be displayed once the data is loaded.

Running the Application

Finally, we can run our application to see the results of our code. Run the following command in your terminal:

npm start
Enter fullscreen mode Exit fullscreen mode

This will start the development server and open up a new tab in your web browser displaying the application. It should look like this.

GraphQl UI rendered

Conclusion

Congratulations! In this article, we walked through the process of fetching data from a GraphQL API using Apollo Client in our React application and how to handle errors that may occur during the process. With this knowledge, you can start building powerful, data-driven user interfaces on your own. Happy coding!

Top comments (12)

Collapse
 
dev_geos profile image
Dev Geos

For django backend, please tell me what is the advantages for using graphql instead of his Orm ?

Collapse
 
joelbonetr profile image
JoelBonetR 🥇 • Edited

Hi,

ORM

Or Object-Relational-Mapping is -usually [0]- meant to mimic DB models as a given programming language classes while providing methods to interact with the forementioned database on a straightforward and secure manner.

In other words, an ORM it's a piece of software (sometimes including a CLI) that helps you interact with a database. You can check SQLAlchemy (Python) or Sequelize (Node) as examples.

GraphQL

in the other hand, is a SDL (Schema Definition Language), it is meant to be a declarative way to interchange information between clients and servers, or between different servers; It falls into the Service layer.
It has some benefits in comparison with RESTful, like being able to define and ask explicitly for different fields from different models on a single request [1]. For this reason it's most of the time used as interface for clients, that sits in the gateway (then the gateway can resolve each requested data piece through API calls to specific microservices).

It has it's drawbacks too, like anything in this life, like being harder to manage the cache on a GraphQL service than in a REST one, though most of the drawbacks have been addressed through the years on a way or another and I'd currently can't find a reason not to provide a GraphQL API unless your use-case doesn't really require it (as always, analysis should be done before taking a stack decision).

Best regards


[0] Usually

There are some exceptions like HaskellDB, which can be considered an ORM as a concept but it uses a FP (Functional Programming) approach.

[1] Example:

You are coding an e-commerce, API-first using microservices architecture, one use-case can be to list the items of the last order of a group of clients to recommend some of those to the user in context.

RESTful scenario:

1- Request users.
2- You got full users (bigger payload) but you just needed the IDs.
3- Use this IDs to call (one time for each user) to a different endpoint to get the last Order of each.
4- Again, you just needed the ID of each order, instead you get the entire Order object, for each user.
5- Call to another endpoint to get the product details on each accumulated orderID to retrieve the product data.
6- Finally use the product data to do whatever you needed to do in the first place.

As you can see, those are a bunch of calls, a lot of unnecessary network data transfer and useless payloads.

GraphQL scenario:

1- Define in the Schema which information you need in this given request.
2- Do the request.
3- Use the data to do whatever you need to do.

Foot Notes

GraphQL and ORM are completely different things, not exclusive between each other.
You will probably keep using an ORM to interact with your DB in a GraphQL service, while GraphQL will be the API exposed to the clients (or other services) to interact with.

Collapse
 
icyybee profile image
Beatrice Egumandi

Thank you for your contribution!!

Thread Thread
 
joelbonetr profile image
JoelBonetR 🥇

Anytime 😁

Collapse
 
icyybee profile image
Beatrice Egumandi • Edited

Thanks for your comment! I'm sorry that I'm not into backend development, so I won't be of much help to you in this case. However, I would recommend that you do your own research to find the best solution.

Collapse
 
yeezywest profile image
Yusuf olatunji adeshina

nicee!!!!!!!!!!!!!!! thank you for the step by step guide🙌🙌🚀🚀😎😎

Collapse
 
icyybee profile image
Beatrice Egumandi

You’re welcome

Collapse
 
thekelvinperez profile image
TheKelvinPerez

Amazing Beatrice Thank you for sharing ❤️

Collapse
 
icyybee profile image
Beatrice Egumandi

I appreciate 😁

Collapse
 
vulcanwm profile image
Medea

great work!

Collapse
 
icyybee profile image
Beatrice Egumandi

Thank you!

Collapse
 
fimber01 profile image
Fimber Elemuwa

Great work!