4 min read · Aug 2, 2023
In this guide, we will learn how to fetch data from APIs in a React.js application. Fetching data from external APIs is a common task in modern web development, and React provides a convenient way to perform these API requests and handle the retrieved data.
We’ll start from scratch and follow these steps to implement data fetching:
- Set Up a New React.js Project
- Create a Component for Fetching Data
- Perform the API Request
- Handle the API Response
- Display the Data in the Component
- Handle Loading and Error States
Let’s get started!
First, make sure you have Node.js and npm (Node Package Manager) installed on your system. Then, create a new React.js project using Create React App:
npx create-react-app data-fetching-app
cd data-fetching-app
React.js follows a component-based architecture, where the user interface is divided into small, reusable components. In this step, we create a new functional component called DataFetcher
.
A functional component is a simple JavaScript function that returns JSX (JavaScript XML) to define the component’s UI. It’s a lightweight way to create components, and with the introduction of React hooks, we can use state and other React features without writing a class-based component.
Here’s the code for the DataFetcher
component:
import React, { useEffect, useState } from 'react';
const DataFetcher = () => {
const [data, setData] = useState([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null); // ...
};
The useState
hook is used to declare three pieces of state: data
, loading
, and error
. We use array destructuring to get the state variable and its setter function. The data
state will hold the fetched data, loading
will represent whether the data is being fetched, and error
will store any errors that occur during the API request.
In this step, we create the fetchData
function to make an API request using the fetch
function. The fetch
function is a modern browser API that allows us to make network requests to the specified URL.
Here’s the relevant part of the code:
const fetchData = async () => {
try {
const response = await fetch('https://api.example.com/data'); // Replace with your API endpoint
if (!response.ok) {
throw new Error('Network response was not ok.');
}
const data = await response.json();
setData(data);
setLoading(false);
} catch (error) {
setError(error.message);
setLoading(false);
}
};
We use the try...catch
block to handle both successful and failed API responses. If the response is successful (status code 200), we parse the JSON response using response.json()
, set the data using setData
, and set the loading
state to false
since data fetching is complete. If the response is not successful (status code other than 200), we throw an error and set the error
state with the error message.
Remember to replace 'https://api.example.com/data'
with the actual URL of the API you want to fetch data from.
In this step, we discuss how we handle the API response inside the fetchData
function.
If the API request is successful and the data is retrieved successfully, we update the component state with the received data:
setData(data);
setLoading(false);
The setData
function updates the data
state with the received data, and setLoading(false)
indicates that the data fetching process is complete.
If the API request encounters an error (such as network issues or server errors), we handle the error inside the catch
block:
setError(error.message);
setLoading(false);
The setError
function sets the error
state with the error message, and setLoading(false)
indicates that the data fetching process is complete (even though it resulted in an error).
Now, let’s update the return
statement in the DataFetcher
component to display the fetched data or appropriate loading/error messages:
return (
<div>
{loading ? (
<p>Loading...</p>
) : error ? (
<p>Error: {error}</p>
) : (
<ul>
{data.map((item) => (
<li key={item.id}>{item.name}</li>
))}
</ul>
)}
</div>
);
This code snippet displays a loading message while data is being fetched, an error message if there was an issue, and the list of data items if the fetch was successful.
As you can see, we are utilizing loading
and error
states to handle different scenarios during the API request. These states help us provide feedback to users about the current status of the data fetch. You can customize the loading and error messages based on your application's requirements.
Finally, integrate the DataFetcher
component into your main application component or any other component as per your application's structure.
That’s it! Now you have a fully functional React.js component that can fetch data from an API and display it in your application.
Remember to handle error scenarios gracefully and implement any additional error handling or data transformation based on your specific use case.
// src/components/DataFetcher.jsimport React, { useEffect, useState } from 'react';
const DataFetcher = () => {
const [data, setData] = useState([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
fetchData();
}, []);
const fetchData = async () => {
try {
const response = await fetch('https://api.example.com/data'); // Replace with your API endpoint
if (!response.ok) {
throw new Error('Network response was not ok.');
}
const data = await response.json();
setData(data);
setLoading(false);
} catch (error) {
setError(error.message);
setLoading(false);
}
};
return (
<div>
{loading ? (
<p>Loading...</p>
) : error ? (
<p>Error: {error}</p>
) : (
<ul>
{data.map((item) => (
<li key={item.id}>{item.name}</li>
))}
</ul>
)}
</div>
);
};
export default DataFetcher;
Happy coding!