Managing Asynchronous Calls with React using Fetch or Axios

Managing Asynchronous Calls with React using Fetch or Axios

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:

  • Fetch API (built-in JavaScript method)
  • Axios (third-party library with additional features)

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:

  • The useEffect hook runs the API call when the component mounts.
  • fetch is used to get data from an API.
  • setLoading(false) updates the state after the request is complete.
  • Errors are caught using .catch().


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

fetch('https://jsonplaceholder.typicode.com/posts')

? .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

axios.post('https://jsonplaceholder.typicode.com/posts', {

? 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!

?https://handbookofsuresh.blogspot.com/2025/02/managing-asynchronous-calls-with-react.html

要查看或添加评论,请登录

Suresh Kumar Rajendran的更多文章

  • Shrinking a Database in SQL Server

    Shrinking a Database in SQL Server

    Shrinking a Database in SQL Server Shrinking a database in SQL Server is the process of reducing the physical size of…

    1 条评论
  • DATALENGTH() - How to find the data size in a column of SQL server table for each row

    DATALENGTH() - How to find the data size in a column of SQL server table for each row

    Finding the data size of individual columns for each row in an SQL Server table requires using the DATALENGTH()…

  • Summary Link of SQL Sever Blog Pages

    Summary Link of SQL Sever Blog Pages

    User-Defined Functions (UDFs) in SQL Server https://handbookofsuresh.blogspot.

  • Role-Based Access Control in SQL Server

    Role-Based Access Control in SQL Server

    Role-Based Access Control (RBAC) in SQL Server is a fundamental security mechanism that allows database administrators…

  • What is Scope Creep: How to Prevent It: (Strategies and techniques)

    What is Scope Creep: How to Prevent It: (Strategies and techniques)

    Scope creep is a common challenge in project management. It refers to the uncontrolled expansion of a project's scope…

  • Synonyms in SQL Server

    Synonyms in SQL Server

    Synonyms in SQL Server In SQL Server, synonyms provide an alternative name for a database object. This can be very…

    1 条评论
  • Heap Bloat in SQL Server

    Heap Bloat in SQL Server

    Heap Bloat in SQL Server Heap bloat in SQL Server occurs when a table that does not have a clustered index (a heap)…

  • Database Shrink in SQL Server

    Database Shrink in SQL Server

    Database Shrink in SQL Server Database Shrinking is the process of reclaiming unused space in a SQL Server database by…

    1 条评论
  • DevOps Tools & Technologies

    DevOps Tools & Technologies

    DevOps Tools & Technologies DevOps relies on various automation tools to streamline development, deployment, and…

  • Ledger Tables for Immutable Data in SQL Server 2022

    Ledger Tables for Immutable Data in SQL Server 2022

    Ledger Tables for Immutable Data in SQL Server SQL Server Ledger Tables provide tamper-evident and immutable data…

    1 条评论

社区洞察