OnlineCBT Logo OnlineCBT
React Tutorial
REACT · LESSON 14

Data Fetching from REST APIs (Axios / Fetch)

By Ratan Updated: 16 Oct 2026

Fetch, create, update, and delete remote API resources using Axios or native fetch inside React components.

Level: Beginner to Advanced
Duration: ~60 Mins Deep-Dive

1. The Async Data Lifecycle

Whenever a React component fetches records from an external backend API, the user interface moves through three distinct states:

  1. Loading: Request is in flight (render skeleton or spinner).
  2. Error: Request failed due to network error, 401 Unauthorized, or 500 Server Error.
  3. Success: Data arrived successfully (render content).

2. Fetching with Native fetch() API

import { useState, useEffect } from 'react';

function CourseList() {
  const [courses, setCourses] = useState([]);
  const [isLoading, setIsLoading] = useState(true);
  const [errorMessage, setErrorMessage] = useState("");

  useEffect(() => {
    const controller = new AbortController(); // For request cancellation

    async function loadCourses() {
      try {
        setIsLoading(true);
        const res = await fetch("https://onlinecbt.in/ibs/api/technical-learning/courses", {
          signal: controller.signal
        });
        if (!res.ok) throw new Error(`Server returned status ${res.status}`);
        const json = await res.json();
        setCourses(json.data || []);
      } catch (err) {
        if (err.name !== "AbortError") {
          setErrorMessage(err.message);
        }
      } finally {
        setIsLoading(false);
      }
    }

    loadCourses();

    // Cleanup: cancel request if component unmounts before response returns
    return () => controller.abort();
  }, []);

  if (isLoading) return 
Loading courses...
; if (errorMessage) return
Error: {errorMessage}
; return (
    {courses.map(c =>
  • {c.name}
  • )}
); }

3. Using Axios

Axios is widely preferred for production apps because it automatically serializes JSON, supports request/response interceptors (for injecting JWT Bearer tokens), and throws automatically on HTTP error statuses (4xx, 5xx).

📝 Live Lesson Practice

HTML/CSS JavaScript Python C++ C PHP
⌨️ Practice Inputs (लाइव इनपुट भरें) (खाली होने पर RED, भरने पर GREEN underline)
💻 Code Editor (Monaco VS Code Engine)
👀 Live Preview
Address Contact

+91 7877547686

E-mail

onlinecbtportal@gmail.com

Helpline Number

+91 7877547686


Click To Download
Get it on Google Play

ऐप डाउनलोड करने
के लिए Google Play पर
उपलब्ध है

WhatsApp Chat