In the dynamic world of ReactJS, using a function like fetch is often inevitable when it comes to making HTTP requests. While there are other libraries like Axios, Fetch API is a part of the browser and can be used to send HTTP requests from the browser. Let's dive into the world of "fetch" in ReactJS, guided with real-world examples.

We'll explore how to use fetch, handle responses, and manage asynchronous operations in ReactJS. By the end of this article, you'll have a comprehensive understanding of how to use fetch in ReactJS, along with useful tips and common pitfalls to avoid.

Understanding Fetch in ReactJS
ReactJS uses JavaScript's Fetch API for making HTTP requests. This API is built into modern browsers and provides a more powerful and flexible way to send HTTP requests compared to old XMLHttpRequest or jQuery's $.ajax.

The fetch function returns a Promise that resolves to the Response object representing the response to the request. Most commonly, you'll use this with async/await for cleaner, more readable code.
Making a Simple GET Request

Here's a basic example of making a GET request in ReactJS using fetch:
const getUsers = async () => {
const response = await fetch('https://jsonplaceholder.typicode.com/users');
const data = await response.json();
console.log(data);
};
In this example, we're fetching data from a public API and logging the response to the console as JSON.
Handling Errors in Promise

It's crucial to handle errors in your fetch requests. Here's how you can do that:
const getUsers = async () => {
try {
const response = await fetch('https://jsonplaceholder.typicode.com/users');
if (!response.ok) {
throw new Error('Network response was not ok');
}
const data = await response.json();
console.log(data);
} catch (error) {
console.log('There has been a problem with your fetch operation:', error);
}
};
In this example, we're checking if the response status is ok (a status of 200-299). If not, we throw an error. If there is any catchable error, we log it to the console.
Using Fetch in React Components

Now that we understand how to use fetch, let's integrate it into a React component.
In this example, we'll fetch data from a public JSON API and display it in our component:



















Fetch Data on Component Mount
import React, { useEffect, useState } from 'react';
const UserList = () => {
const [data, setData] = useState([]);
useEffect(() => {
const fetchData = async () => {
const response = await fetch('https://jsonplaceholder.typicode.com/users');
const json = await response.json();
setData(json);
};
fetchData();
}, []);
return (
{data.map((user) => (
- {user.name}
))}
); };
Here, we're using the useEffect hook to fetch data when the component mounts. The fetched data is then displayed in a list.
Fetch Data on Button Click
You can also use fetch to fetch data based on user interaction, like a button click:
import React, { useState } from 'react';
const UserList = () => {
const [data, setData] = useState([]);
const fetchData = async () => {
const response = await fetch('https://jsonplaceholder.typicode.com/users');
const json = await response.json();
setData(json);
};
return (
{data.map((user) => (
- {user.name}
))}
);
};
In this example, clicking the "Load Data" button triggers the fetchData function, which fetches data and updates the component's state.
As you become more comfortable with fetch in ReactJS, you can incorporate it into more complex components and applications. Happy coding, and may your fetch requests always be ok!