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 i…


This content originally appeared on DEV Community 👩‍💻👨‍💻 and was authored by Beatrice Egumandi

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

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

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>
);

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;

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

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!


This content originally appeared on DEV Community 👩‍💻👨‍💻 and was authored by Beatrice Egumandi


Print Share Comment Cite Upload Translate Updates
APA

Beatrice Egumandi | Sciencx (2023-02-18T22:12:54+00:00) Creating an App with React, Apollo, and GraphQL: A Step-by-Step Guide to Fetching Data and Error Handling. Retrieved from https://www.scien.cx/2023/02/18/creating-an-app-with-react-apollo-and-graphql-a-step-by-step-guide-to-fetching-data-and-error-handling/

MLA
" » Creating an App with React, Apollo, and GraphQL: A Step-by-Step Guide to Fetching Data and Error Handling." Beatrice Egumandi | Sciencx - Saturday February 18, 2023, https://www.scien.cx/2023/02/18/creating-an-app-with-react-apollo-and-graphql-a-step-by-step-guide-to-fetching-data-and-error-handling/
HARVARD
Beatrice Egumandi | Sciencx Saturday February 18, 2023 » Creating an App with React, Apollo, and GraphQL: A Step-by-Step Guide to Fetching Data and Error Handling., viewed ,<https://www.scien.cx/2023/02/18/creating-an-app-with-react-apollo-and-graphql-a-step-by-step-guide-to-fetching-data-and-error-handling/>
VANCOUVER
Beatrice Egumandi | Sciencx - » Creating an App with React, Apollo, and GraphQL: A Step-by-Step Guide to Fetching Data and Error Handling. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2023/02/18/creating-an-app-with-react-apollo-and-graphql-a-step-by-step-guide-to-fetching-data-and-error-handling/
CHICAGO
" » Creating an App with React, Apollo, and GraphQL: A Step-by-Step Guide to Fetching Data and Error Handling." Beatrice Egumandi | Sciencx - Accessed . https://www.scien.cx/2023/02/18/creating-an-app-with-react-apollo-and-graphql-a-step-by-step-guide-to-fetching-data-and-error-handling/
IEEE
" » Creating an App with React, Apollo, and GraphQL: A Step-by-Step Guide to Fetching Data and Error Handling." Beatrice Egumandi | Sciencx [Online]. Available: https://www.scien.cx/2023/02/18/creating-an-app-with-react-apollo-and-graphql-a-step-by-step-guide-to-fetching-data-and-error-handling/. [Accessed: ]
rf:citation
» Creating an App with React, Apollo, and GraphQL: A Step-by-Step Guide to Fetching Data and Error Handling | Beatrice Egumandi | Sciencx | https://www.scien.cx/2023/02/18/creating-an-app-with-react-apollo-and-graphql-a-step-by-step-guide-to-fetching-data-and-error-handling/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.