How to setup GraphQL in React App
GraphQL is a query language for application programming interfaces (APIs). It offers efficient alternatives to
Below is the detailed explanation on how to setup
Install Apollo Client
Before getting started, make sure you have the React project setup and running.
Install React project in your React project directory using either npm or yarn.
Using
npm
npm is linked to Node.js which means that if you install Node.js, npm will be automatically installed in your system.
npm install @apollo/client graphql
Using
yarn
You need to install yarn separately. After the installation of Node.js, install yarn as given below.
npm install -g yarn
yarn add @apollo/client graphql
Setup a new client
We will use Apollo Client which is a library to simplify the management of local and remote data with GraphQL.
Create a new JavaScript file called client.js in the following directory:
|-- src|-- AppolloClient|-- client.js
Add the following code to it.
import {ApolloClient, InMemoryCache} from '@apollo/client';const client = new ApolloClient({uri: 'http://localhost:5000/graphql',cache: new InMemoryCache(),});
Here,
Line 4: You need to replace the
with your GraphQL server URI. If you are using a local server, URI is the same as mentioned in line 4 except the port number. If you are using an external server, check theuriUniform Resource Identifier to find the exact URI for the server you are using.documentation https://www.apollographql.com/docs/react/api/link/apollo-link-http Line 5:
InMemoryCache()class activates the cache. You need to set up this class on the client side to handle the data received from the server. It prevents you from making unnecessary network requests by keeping multiple files of the data.
Connect Apollo Client to React App
To allow the child components to make queries, update "src/App.js" file to add the client configuration.
import React from "react";import ReactDOM from 'react-dom';import App from './App';import client from "./ApolloClient/client";import { ApolloProvider } from '@apollo/client';import Books from './Books';function App(){return (<ApolloProvider client = {client}><div className = "App"><Books /></div></ApolloProvider>);}export default App;
Here,
Line 1–6: We make all the necessary imports.
Line 12–16: The
clientset earlier is imported here. Everything is wrapped inside theApolloProvidercomponent. It is necessary to make these changes so that the componentBooksknows how to fetch data from the server. TheBookscomponents may vary according to your React app.
Make a GraphQL query
Create a JavaScript file in the following directory:
|-- src|-- Books.js
You can add the following code to it:
import React from 'react';import { useQuery, gql } from '@apollo/client';// GraphQL query to fetch a list of booksconst GET_BOOKS = gql`// write your query herequery GET_BOOKS {books {titleauthor}}`;function Books(){const {data, loading, error} = useQuery(GET_BOOKS);if (loading)return <div>Loading...</div>;if (error)return <div>Error</div>;return data.books.map(({title, author}, index) => (<div key={index}><div>{`${title} by ${author}`}</div></div>));}export default Books;
Here,
Line 5:
GET_BOOKS = gqlspecifies a GraphQL query to fetch a list of books, each with its title and author.Line 17:
use_Query(GET_BOOKS)usesuseQueryhook to query the server. It aids in rendering and populating the components and returns an object withdata,loadinganderrorproperties.Line 19–20: The component renders a
loadingmessage if the query is still loading.Line 21–22: The component renders an
errormessage if there is an error executing the query.Line 24–27: The component
map, maps the list of books by rendering thetitle,author, and paragraph for each book indata.books.
Whenever the component above is loaded, it sends a query to the server and the loading is set to true. Once the server returns the data, the component is rendered immediately. The data is populated with all the data being fetched from the server.
Note: You can replace the
GET_BOOKSwith your GraphQLquery.
The instructions mentioned above provide the basic setup that should get you started with GraphQL in the React app.
Unlock your potential: GraphQL series, all in one place!
If you've missed any part of the series, you can always go back and check out the previous Answers:
What is GraphQL?
Get an overview of GraphQL, its core principles, and how it enhances API interactions.What are abstract types in GraphQL?
Understand abstract types like interfaces and unions, and how they provide flexibility in your GraphQL queries.What are non-null constraints in GraphQL?
Discover the role of non-null constraints in ensuring data integrity within GraphQL schemas.What are different ways to pass an argument in GraphQL?
Explore various methods for passing arguments in GraphQL to customize queries and mutations for specific needs.GraphQL vs. REST
Compare GraphQL with REST, understanding the strengths and differences between the two approaches.How to set up GraphQL in a React app
Learn how to integrate GraphQL into React apps to create dynamic, data-driven user interfaces.
Free Resources