Fetch Data in React Components
Apollo Client Method
Using Apollo Client to fetch data in your React application
// 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;
We can use useQuery to fetch data within the react component named UserList from the GraphQL API in the above way as written in the code. The code is explained:
Importing the required dependencies:
- useQuery is imported from @apollo/client package . This hook lets you ask GraphQL questions within your react component.
- GET_USERS is the query you wrote earlier and it is imported from the ../queries file. This is the query you wrote asking for a list of users
UserList component: This part of the code creates a list to show the users. It is a functional component that utilizes the useQuery hook to execute the GET_USERS query.
The hook returns an object with properties such as loading, error, and data.
- Loading: If the answer is still on its way, the component shows a “Loading…” message.
- Errors: If something unexpected happens the error message can help us in debugging.
- When the data is successfully fetched it is rendered within the react component. The component renders a list of users with name and email. The key attribute is set to user.id for React’s list rendering optimization
Key points:
- The useQuery hook is a special tool for asking GraphQL questions within the react component
- It handles different states such as loading, error, and success to make sure the user experience is smooth.
Fetch API
Use the fetch API in a React Component:
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;
In the above code :
- GET_USERS is a query string containing the GraphQL query.
- Fetch API makes a POST request to the GraphQL API endpoint with the GraphQL in the request body.
- The component has states (loading, error, and users) to manage the asynchronous data.
- The useEffect hook ensures that the data is fetched only after the component mounts.
Axios Library
Using the axios library if we want to fetch data follow the below code:
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;
- Axios library is used to make a POST request to the GraphQL API endpoint with GraphQL query in the request body
- The component has states (loading, error, and users) to manage the asynchronous data.
- The useEffect hook ensures that the data is fetched only after the component mounts.
How to Integrate GraphQL APIs Into Your React.js Projects
Imagine a React.js world where you can specify exactly the data you need and it flows effortlessly tailored to your needs, and react can efficiently update the DOM as and when needed. No more under-fetching or over-fetching of data or wrestling with nested JSON structures.
This dream becomes a reality with the use of GraphQL the rising star of API technology. This article aims to help you integrate the GraphQL API with your React project.
Table of Content
- What is GraphQL
- Why GraphQL
- How to Integrate GraphQL APIs into Your React.js Projects
- Step 1: Set Up a React Application
- Step 2: Install Required Packages
- Step 3: Using Apollo, Configure the Apollo Client
- Step 4: Create GraphQL Queries
- Step 5: Fetch Data in React Components
- Step 6: Display Data in Your React App
- Step 7: Run Your Application