Managing Asynchronous Calls with React using Fetch or Axios
Suresh Kumar Rajendran
Head of R&D | Building Framework for ERP product | .Net | C# | SQL | React | Kendo | JavaScript| PMO | Construction Domain ERP | Initiation of AI based ERP
Managing Asynchronous Calls with React using Fetch or Axios
Handling asynchronous calls in React is essential for fetching data from APIs, submitting forms, and interacting with databases. The two most common methods for making asynchronous HTTP requests in React are:
In this guide, we will cover:
? Using Fetch API
? Using Axios
? Handling errors
? Using useEffect and useState for API calls
? Displaying loading states
1. Fetch API in React
The fetch function is a built-in JavaScript method for making HTTP requests.
Example: Fetching Data from an API
import React, { useState, useEffect } from 'react';
?
function FetchExample() {
? const [data, setData] = useState([]);
? const [loading, setLoading] = useState(true);
? const [error, setError] = useState(null);
?
? useEffect(() => {
??? fetch('https://jsonplaceholder.typicode.com/posts')
????? .then((response) => {
????? ??if (!response.ok) {
????????? throw new Error('Failed to fetch data');
??????? }
??????? return response.json();
????? })
????? .then((data) => {
??????? setData(data);
??????? setLoading(false);
????? })
????? .catch((error) => {
??????? setError(error.message);
??????? setLoading(false);
????? });
? }, []);
?
? if (loading) return <p>Loading...</p>;
? if (error) return <p>Error: {error}</p>;
?
? return (
??? <div>
????? <h2>Posts</h2>
????? <ul>
??????? {data.slice(0, 5).map((post) => (
????????? <li key={post.id}>{post.title}</li>
??????? ))}
????? </ul>
??? </div>
? );
}
?
export default FetchExample;
How It Works:
2. Axios in React
Axios is a popular library for making HTTP requests and provides additional features like automatic JSON parsing, request cancellation, and better error handling.
Installation
Run the following command to install Axios:
npm install axios
Example: Fetching Data Using Axios
import React, { useState, useEffect } from 'react';
import axios from 'axios';
?
function AxiosExample() {
? const [data, setData] = useState([]);
? const [loading, setLoading] = useState(true);
? const [error, setError] = useState(null);
?
? useEffect(() => {
??? axios.get('https://jsonplaceholder.typicode.com/posts')
????? .then((response) => {
??????? setData(response.data);
??????? setLoading(false);
????? })
????? .catch((error) => {
??????? setError(error.message);
??????? setLoading(false);
????? });
? }, []);
?
? if (loading) return <p>Loading...</p>;
? if (error) return <p>Error: {error}</p>;
?
? return (
??? <div>
????? <h2>Posts</h2>
????? <ul>
??????? {data.slice(0, 5).map((post) => (
????????? <li key={post.id}>{post.title}</li>
??????? ))}
????? </ul>
??? </div>
? );
}
?
export default AxiosExample;
Why Use Axios?
? Automatically converts response to JSON.
? Supports request and response interceptors.
? Easier to cancel requests.
? Handles errors better than Fetch API.
3. Handling API Errors Gracefully
Both Fetch and Axios require proper error handling.
Handling Errors with Fetch
? .then((response) => {
??? if (!response.ok) {
????? throw new Error('Something went wrong');
??? }
??? return response.json();
? })
? .catch((error) => console.error('Fetch Error:', error.message));
Handling Errors with Axios
Axios automatically rejects failed HTTP status codes, making error handling easier:
axios.get('https://jsonplaceholder.typicode.com/posts')
??.then((response) => console.log(response.data))
? .catch((error) => console.error('Axios Error:', error.message));
4. Posting Data with Fetch and Axios
POST Request Using Fetch
fetch('https://jsonplaceholder.typicode.com/posts', {
? method: 'POST',
? headers: {
??? 'Content-Type': 'application/json',
? },
? body: JSON.stringify({ title: 'New Post', body: 'This is a new post' }),
})
? .then((response) => response.json())
? .then((data) => console.log('Success:', data))
? .catch((error) => console.error('Error:', error));
POST Request Using Axios
? title: 'New Post',
? body: 'This is a new post',
})
? .then((response) => console.log('Success:', response.data))
? .catch((error) => console.error('Error:', error));
5. Using Async/Await for Cleaner Code
Instead of .then() and .catch(), you can use async/await for better readability.
Example with Fetch
async function fetchData() {
? try {
??? let response = await fetch('https://jsonplaceholder.typicode.com/posts');
??? if (!response.ok) throw new Error('Network response was not ok');
??? let data = await response.json();
??? console.log(data);
? } catch (error) {
??? console.error('Error:', error);
? }
}
?
fetchData();
Example with Axios
async function fetchData() {
? try {
??? let response = await axios.get('https://jsonplaceholder.typicode.com/posts');
??? console.log(response.data);
? } catch (error) {
??? console.error('Error:', error);
? }
}
?
fetchData();
6. Cancelling API Requests to Prevent Memory Leaks
When a component unmounts, ongoing API calls can cause errors. Axios provides an easy way to cancel requests.
Example: Cancelling API Request in Axios
import React, { useState, useEffect } from 'react';
import axios from 'axios';
?
function CancelableRequest() {
? const [data, setData] = useState([]);
?
? useEffect(() => {
??? const source = axios.CancelToken.source();
?
??? axios.get('https://jsonplaceholder.typicode.com/posts', { cancelToken: source.token })
????? .then((response) => setData(response.data))
????? .catch((error) => {
??????? if (axios.isCancel(error)) {
????????? console.log('Request canceled:', error.message);
??????? } else {
????????? console.error('API Error:', error);
??????? }
????? });
?
??? return () => {
????? source.cancel('Component unmounted, request cancelled');
??? };
? }, []);
?
? return (
??? <div>
????? <h2>Data Loaded</h2>
????? <p>{data.length} items fetched</p>
??? </div>
? );
}
?
export default CancelableRequest;
Conclusion
? Use Fetch if you want a simple, native solution without extra dependencies.
? Use Axios for enhanced error handling, request cancellation, and simpler syntax.
? Always handle errors to avoid breaking the UI.
? Use async/await for cleaner code.
? Cancel API requests to prevent memory leaks.
Now you can efficiently manage API calls in your React applications!