How to Integrate a GraphQL API with Your React.js Application

In this blog post, we will learn how to integrate a GraphQL API with your React.js application. GraphQL is a powerful query language that allows clients to request only the data they need, reducing the amount of data transmitted over the network. React is a popular JavaScript library for building user interfaces, and when combined with GraphQL, it can lead to more efficient and flexible applications. In this tutorial, we will cover the basics of GraphQL, how to set up a simple React application, and how to integrate a GraphQL API with your React app. This guide is beginner-friendly, so don't worry if you're new to React or GraphQL.

Prerequisites

Before we get started, make sure you have the following installed on your machine:

  1. Node.js (version 12 or higher)
  2. npm (version 6 or higher)
  3. A code editor of your choice (we recommend Visual Studio Code)

Setting Up the React Project

First, we need to set up a basic React project. To do this, we'll use the popular create-react-app command-line tool. Open your terminal and run the following command to create a new React app:

npx create-react-app graphql-react-app

Once the process is finished, navigate to the newly created project directory:

cd graphql-react-app

Now you can start the development server by running:

npm start

Your React app should be running on http://localhost:3000. You can now open your code editor and start working on the project.

Introduction to GraphQL

GraphQL is a query language and runtime for APIs that was developed by Facebook. It providesa flexible and efficient way to request and manipulate data. With GraphQL, you can request only the data you need, which helps reduce the amount of data sent over the network.

In a typical REST API, you would have multiple endpoints for different data resources, and you would need to make multiple requests to fetch related data. With GraphQL, there is a single endpoint that you send queries to, and you can request related data in a single query.

To understand how GraphQL works, let's quickly go through some key concepts:

  • Queries: Queries are the way you request data from a GraphQL API. You can think of them as similar to GET requests in a REST API.
  • Mutations: Mutations are used to modify data in the GraphQL API. They are like POST, PUT, and DELETE requests in a REST API.
  • Schema: The schema defines the types and structure of the data that can be queried or mutated. It serves as a contract between the client and the server.
  • Resolvers: Resolvers are functions that handle how the data is fetched or modified for each field in the schema.

Now that we have a basic understanding of GraphQL, let's move on to integrating it with our React app.

Adding Apollo Client to Your React App

To integrate a GraphQL API with a React application, we'll use Apollo Client, a popular and feature-rich GraphQL client for React. It provides a set of tools and components to make it easier to work with GraphQL APIs in a React app.

First, let's install the required packages:

npm install @apollo/client graphql

Now, let's create an instance of Apollo Client. In the src directory, create a new filecalled apolloClient.js. Inside this file, add the following code to set up the Apollo Client:

import { ApolloClient, InMemoryCache } from '@apollo/client'; const client = new ApolloClient({ uri: 'https://your-graphql-api-endpoint.com', cache: new InMemoryCache() }); export default client;

Make sure to replace https://your-graphql-api-endpoint.com with the actual endpoint of your GraphQL API.

Next, we need to wrap our React app with the ApolloProvider component, which comes from the @apollo/client package. This component will provide the Apollo Client instance to all the components in our app.

Open the src/index.js file and modify it as follows:

import React from 'react'; import ReactDOM from 'react-dom'; import { ApolloProvider } from '@apollo/client'; import client from './apolloClient'; import App from './App'; import './index.css'; ReactDOM.render( <React.StrictMode> <ApolloProvider client={client}> <App /> </ApolloProvider> </React.StrictMode>, document.getElementById('root') );

Now that we have our Apollo Client set up, we can start making queries and mutations in our React app.

Fetching Data with GraphQL Queries

Let's say our GraphQL API has a books query that returns a list of books with their title and author. To fetch this data in our React app, we'll use the useQuery hook provided by the @apollo/client package.

First, let's create a new file in the src directory called BookList.js. This component will be responsible for fetching and displayingthe list of books.

Inside the BookList.js file, add the following code:

import React from 'react'; import { useQuery, gql } from '@apollo/client'; const BOOKS_QUERY = gql` query GetBooks { books { id title author } } `; const BookList = () => { const { loading, error, data } = useQuery(BOOKS_QUERY); if (loading) return <p>Loading...</p>; if (error) return <p>Error: {error.message}</p>; return ( <div> <h2>Book List</h2> <ul> {data.books.map(book => ( <li key={book.id}> {book.title} by {book.author} </li> ))} </ul> </div> ); }; export default BookList;

In this component, we define the BOOKS_QUERY using the gql template tag. This query requests a list of books with their id, title, and author. The useQuery hook is then used to fetch this data. The loading, error, and data properties are destructured from the result, and we conditionally render the content based on their values.

Now, let's include the BookList component in our App.js file:

import React from 'react'; import './App.css'; import BookList from './BookList'; function App() { return ( <div className="App"> <header className="App-header"> <h1>GraphQL and React Integration</h1> </header> <main> <BookList /> </main> </div> ); } export default App;

With these changes, our React app should now display the list of books fetched from the GraphQL API.

Adding Data with GraphQL Mutations

Now let's see how we can add new data to our GraphQL API using mutations. We'll create a form to add new books to our list.

First, create a new file in the src directory called AddBook.js. Inside this file, add the following code:

import React, { useState } from 'react'; import { useMutation, gql } from '@apollo/client'; const ADD_BOOK_MUTATION = gql` mutation AddBook($title: String!, $author: String!) { addBook(title: $title, author: $author) { id title author } } `; const AddBook = () => { const [title, setTitle] = useState(''); const [author, setAuthor] = useState(''); const [addBook] = useMutation(ADD_BOOK_MUTATION, { variables: { title: title, author: author }, refetchQueries: ['GetBooks'] }); const handleSubmit = async (e) => { e.preventDefault(); await addBook(); setTitle(''); setAuthor(''); }; return ( <div> <h2>Add a Book</h2> <form onSubmit={handleSubmit}> <label htmlFor="title">Title:</label> <input type="text" id="title" value={title} onChange={(e) => setTitle(e.target.value)} /> <br /> <label htmlFor="author">Author:</label> <input type="text" id="author" value={author} onChange={(e) => setAuthor(e.target.value)} /> <br /> <button type="submit">Add Book</button> </form> </div> ); }; export default AddBook;

In this component, we define the ADD_BOOK_MUTATION using the gql template tag. This mutation takes two arguments, title and author, and returns the newly added book's id, title, and author. The useMutation hook is used to execute this mutation, and we pass the variables object with the values of title and author from our component state.

To automatically update the list of books after adding a new book, we use the refetchQueries option to refetch the GetBooks query.

Now, let's include the AddBook component in our App.js file:

import React from 'react'; import './App.css'; import BookList from './BookList'; import AddBook from './AddBook'; function App() { return ( <div className="App"> <header className="App-header"> <h1>GraphQL and React Integration</h1> </header> <main> <BookList /> <AddBook /> </main> </div> ); } export default App;

With these changes, our React app should now display a form to add new books, and the book list should update automatically after a new book is added.

FAQ

1. What is GraphQL, and how is it different from REST?

GraphQL is a query language and runtime for APIs developed by Facebook. It allows clients to request only the data they need, reducing the amount of data sent over the network. In a REST API, you have multiple endpoints for different data resources, and you need to make multiple requests to fetch related data. With GraphQL, there is a single endpoint that you send queries to, and you can request related data in a single query.

2. What is Apollo Client, and why do we use it with React?

Apollo Client is a popular and feature-rich GraphQL client for React. It provides a set of tools and components to make it easier to work with GraphQL APIs in a React app. By using Apollo Client, you can easily fetch, cache, and manage the state of your GraphQL data in your React application.

3. Can I use other GraphQL clients with React?

Yes, you can use other GraphQL clients with React, such as Relay or urql. Each client has its own set of features and trade-offs. Apollo Client is popular due to its extensive features, good documentation, and active community.

4. How can I handle errors while fetching or mutating data with Apollo Client?

When using the useQuery anduseMutation hooks, you can destructure the error property from the result. This property will contain any error information that occurred while fetching or mutating data. You can then conditionally render error messages or handle the error in a way that suits your application.

For example:

const { loading, error, data } = useQuery(BOOKS_QUERY); if (error) return <p>Error: {error.message}</p>;

5. How can I optimize performance and prevent unnecessary re-fetching of data with Apollo Client?

Apollo Client provides a built-in caching mechanism to optimize performance and prevent unnecessary re-fetching of data. By default, it uses the InMemoryCache for caching query results.

Additionally, you can use the fetchPolicy option in the useQuery hook to control how your query interacts with the cache. Some common fetch policies are:

  • cache-first: (default) This policy will try to read the data from the cache first. If the data is not available in the cache, it will fetch the data from the network.
  • network-only: This policy will always fetch the data from the network, bypassing the cache.
  • cache-and-network: This policy will first return the data from the cache (if available) and then fetch the data from the network, updating the cache with the new data.

For example:

const { loading, error, data } = useQuery(BOOKS_QUERY, { fetchPolicy: 'cache-and-network' });

Conclusion

In this blog post, we have covered how to integrate a GraphQL API with a React.js application. We learned thebasics of GraphQL, how to set up a simple React application, and how to use Apollo Client to fetch and manipulate data from a GraphQL API.

By using GraphQL with React, you can build more efficient and flexible applications that only request the data they need, resulting in a better user experience and improved performance. With the help of Apollo Client, you can easily manage your GraphQL data in your React app, handling caching, state management, and error handling.

We hope this tutorial has provided you with a solid foundation for integrating GraphQL APIs with your React applications. Keep exploring and experimenting with GraphQL and React to build amazing and efficient applications.

Become The Best React Developer 🚀
Codedamn is the best place to become a proficient developer. Get access to hunderes of practice React.js courses, labs, and become employable full-stack React web developer.

Unlimited access to all platform courses

100+ practice projects included

ChatGPT Based Instant AI Help

Structured React.js/Next.js Full-Stack Roadmap To Get A Job

Exclusive community for events, workshops

Create A Free Account

Sharing is caring

Did you like what Mehul Mohan wrote? Thank them for their work by sharing it on social media.

0/20000

No comments so far