With the advent of the technological era, it is important that you are well aware about the technical tools that are now available and that can make working with APIs easier.
One such tool is GraphQL, it basically helps you to fetch data with the help of queries.
A query can be rightly defined as a GraphQL Operation that assists you in searching the specific targeted data in one go. This ensures that you do not have to over-fetch or under-fetch the data while working with API technology. By considering this approach, you get the opportunity to work with React,js seamlessly as you can fetch desired data that is tailored to your need without wasting time and resources.
In this guide, you will be walked through the process of using GraphQL, you will also be highlighted with its advantages. By the end of this blog you will be filled with insights on how to integrate GraphQL into your React.js projects and how fetching data from GraphQL has made life easier.
What is GraphQL and the Use of GraphQL in ReactJs?
GraphQL is an open-source data query language for APIs (Application Programming Interface). It can also be termed a query runtime engine for fulfilling your queries with the existing data. GraphQL is undoubtedly a client-oriented data language as it allows them to create and recreate data in specific structures tailored to their needs. This type of model also enables the client to fetch data efficiently which is very crucial, it also saves time as you don’t have to again and again fetch details from the server.
![](https://blogs.cyaniclab.com/wp-content/uploads/2024/06/Hire-dedicated-developers-team-for-startups-2-1024x171.png)
GraphQL is also a developer-friendly language as it enables them to build APIs the way they want and the specifications of GraphQL ensure that the API behaves as per the client’s expectation, this also makes it adaptable and works effectively.
How to Integrate GraphQL APIs into Your React.js Projects
When you desire to integrate your React.js project with GraphQL, there are three ways to do the same, mainly
- Apollo Client
- React Query + Axios
- React Query + Fetch API
However we won’t let you cling without accurate answers, below is a systematic procedure that will guide you through every change.
STEP – 1 Set up a React Application
You can start by typing the commands below once you open the terminal or the command prompt. As a result, this command entered will help you to create a basic version of the react app with basic configurations.
npx create-react-app graphql-react-app
After this step, you should open the newly created folder.
cd graphql-react-app
In the last step, you can get things going by typing this
npm start
Your app is now ready and is running at http://localhost:3000/
STEP – 2 Install Required Packages
To ease the complexities of the server, a tool that is highly advisable is Apollo Client, it will act as a translator for GraphQL and React, this will make things much more understandable and easier.
npm install @apollo/client graphql
STEP – 3 Using Apollo, Configure the Apollo Client
As mentioned about GraphicQL being a query language, so it can be said that Apollo Client acts as translator for this language React. It has been observed that Apollo Client works consistently with React. The configuration can be achieved by specifying the endpoint.
import { ApolloClient, InMemoryCache, ApolloProvider } from ‘@apollo/client’;
const client = new ApolloClient({
uri: ‘https://your-graphql-api-endpoint.com/graphql’, // Replace with your GraphQL API endpoint
cache: new InMemoryCache()
});
ReactDOM.render(
<ApolloProvider client={client}>
<App />
</ApolloProvider>,
document.getElementById(‘root’)
);
STEP – 4 Create GraphQL Queries
Certainly! Here’s the code snippet with HTML entities applied to display correctly on a webpage:
“`html
// src/queries.js
import { gql } from ‘@apollo/client’;
export const GET_USERS = gql`
query {
users {
id
name
email
// Add other fields you need
}
}
`;
“`
The query that you can see above is an example of how you can create a simple query to fetch a list of users. In simpler words, you just have to precisely write a request for the data you want. Use of the “gql tag” is advisable while writing your GraphicQL questions.
You can find the explanation of the code below –
In this sample code, you can see that the GraphicQL is dissected or divided into query documents that are simpler and understandable by the Apollo Client. The gql function can specifically define queries that are put up, it is then integrated into a javascript code. This gql function is imported from @apollo/client package, this sort of tool makes understanding of GraphicQL questions easier.
Defining GraphQL query – In order to write a query, using the gql tag becomes mandatory. Now data is requested by this written query from GraphicQL API to specify required fields such as ID, name and email.
Query Structure
- Query – Apollo is notified that you are looking for some information by this word.
- Users – This word helps you to fund the specific data you are looking for.
- Fields – These are the required fields that need to be filled,it includes ID, name and email.
STEP – 5 Fetch Data in React Components
Taking into consideration all the three methods –
1. Apollo Client Method
Here’s the code snippet for the `UserList` component with HTML entities applied for displaying correctly on a webpage:
“`html
// src/components/UserList.js
import { useQuery } from ‘@apollo/client’;
import { GET_USERS } from ‘../queries’;
function UserList() {
const { loading, error, data } = useQuery(GET_USERS);
if (loading) return <p>Loading…</p>;
if (error) return <p>Error: {error.message}</p>;
return (
<div>
<h2>User List</h2>
<ul>
{data.users.map(user => (
<li key={user.id}>
{user.name} – {user.email}
</li>
))}
</ul>
</div>
);
}
export default UserList;
“`
In the above mentioned example, you can see how a query is used to fetch data in React component naked UserList from the GraphiQL.
Explanation –
- You can use “useQuery” to ask questions from GraphicQL within React Component. This useQuery is imported from @apollo/client package.
- When you are supposed to ask list of users, GET_USERS is the query that is written and is imported from /queries file.
UserList Components – In this part, a list is created which is then shown to users. This is a functional component that utilises use query hook to perform GraphQL query.
2. Fetch API
“`javascript
import React, { useState, useEffect } from ‘react’;
import { GET_USERS } from ‘../queries’;
function UserList() {
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
const [users, setUsers] = useState([]);
useEffect(() => {
const fetchData = async () => {
try {
const response = await fetch(‘https://your-graphql-api-endpoint.com/graphql’, {
method: ‘POST’,
headers: {
‘Content-Type’: ‘application/json’,
},
body: JSON.stringify({
query: GET_USERS,
}),
});
const result = await response.json();
if (result.errors) {
throw new Error(result.errors[0].message);
}
setUsers(result.data.users);
setLoading(false);
} catch (error) {
setError(error.message);
setLoading(false);
}
};
fetchData();
}, []);
if (loading) return <p>Loading…</p>;
if (error) return <p>Error: {error}</p>;
return (
<div>
<h2>User List</h2>
<ul>
{users.map(user => (
<li key={user.id}>
{user.name} – {user.email}
</li>
))}
</ul>
</div>
);
}
export default UserList;
“`
Explanation –
- GET_USERS contains a GraphQL query.
- A request is made to GraphQL API endpoint by Fetch API.
- The component has different states, loading , error and users.
3. Axios Library
Fetching data using Axios Library.
import React, { useState, useEffect } from ‘react’;
import axios from ‘axios’;
import { GET_USERS } from ‘../queries’;
function UserList() {
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
const [users, setUsers] = useState([]);
useEffect(() => {
const fetchData = async () => {
try {
const response = await axios.post(‘https://your-graphql-api-endpoint.com/graphql’, {
query: GET_USERS,
});
if (response.data.errors) {
throw new Error(response.data.errors[0].message);
}
setUsers(response.data.data.users);
setLoading(false);
} catch (error) {
setError(error.message);
setLoading(false);
}
};
fetchData();
}, []);
if (loading) return <p>Loading…</p>;
if (error) return <p>Error: {error}</p>;
return (
<div>
<h2>User List</h2>
<ul>
{users.map(user => (
<li key={user.id}>
{user.name} – {user.email}
</li>
))}
</ul>
</div>
);
}
export default UserList;
“`
- A POST request to the GraphQL API endpoint is made by using Axios Library.
- The component has states – loading , error and user
- The useEffect ensures that data is found only after component mounts.
STEP – 6 Display Data in your React App
UserList is imported and it uses GraphQL is display the data is fetched nto your react application.
// src/App.js
import React from ‘react’;
import UserList from ‘./components/UserList’;
function App() {
return (
<div>
<h1>GraphQL React App</h1>
<UserList />
</div>
);
}
export default App;
“`
The above code suggests that the app.js is acting as a headquarter for your React application, in other terms it can be called as the entrypoint of the app that controls the overall layout of the application.
- Importing Components – List of users is fetched using GraphQL queries. The UserList is imported into your app.js and is responsible for displaying the data.
- App Component – The app is based on these components, they act as the main building for your application.
The appearance of the app is designed by JSX, it is an approach to write HTML – CODE in React in a unique way.
When everything is placed together, things start working when <UserList/> is placed within the Apps components. The UserList components are presented whenever the app components are presented. So ultimately this makes sure that GraphQL queries are presented as a part of your application’s interface.
STEP – 7 Run Your Application
To start your React Application, run npm start in your terminal and make sure that it properly fetches data from GraphQL API.
npm start
Conclusion
Over the recent times, it has been observed that integration of GraphQL has proven to be efficient in creating web applications. It is a powerful tool to deal with APIs and is successful in managing react components for different APIs. GraphQL is claimed to be the latest technology in API querying when integrated with your React.js projects.
FAQ
Q1. Why use GraphQL over traditional REST APIs?
GraphQL is prioritised because of its “data specific” ability. In comparison to REST APIs, the data is fetched accurately according to the specifications. Unlike other APIs, GraphQL prevents over-fetching and under-fetching.
Q2. What are the three ways to integrate GraphQL APIs into a React.js Project?
The three ways of integrating GraphQL are – Apollo Client, React Query + Axios, React Query + Fetch API.
When you aim to simplify your experience while working with GraphQL, Apollo client is recommended.
Q3. What are the requirements before integrating GraphQL into a React.js project?
Following things are mandatory before you integrat your GraphQL into React.js.
- Node.js (version 12 or higher)
- Npm (version 6b or higher)
- Code Editor