Next

Fetching Data

  • This lesson introduces data fetching in React and explains how to work with APIs and handle responses.

  • Topic Overview

    Modern React applications often need to communicate with servers to fetch or send data.
    This is done using APIs (Application Programming Interfaces).

    Examples:

    • Fetching user data

    • Displaying products

    • Submitting forms

    • Authenticating users

    Fetching Data

    Fetch API Basics

    The Fetch API is a built-in JavaScript method used to make HTTP requests.

    Example:

fetch("https://api.example.com/users")
  .then(res => res.json())
  .then(data => console.log(data));
  • Key Points:

    • Returns a Promise

    • Uses .then() or async/await

    • No extra library needed

    Using Fetch with React

    Usually used inside useEffect.

    Example:

useEffect(() => {
  fetch("/api/users")
    .then(res => res.json())
    .then(data => setUsers(data));
}, []);
  • Runs once when component mounts.

    Axios Introduction

    What is Axios?

    Axios is a popular third-party library for making HTTP requests.

    Why Axios?

     ✅ Automatic JSON parsing
    ✅ Better error handling
    ✅ Request & response interceptors

    Axios Example

import axios from "axios";

axios.get("/api/users")
  .then(response => setUsers(response.data));
  • Fetch vs Axios

    Fetch

    Axios

    Built-in

    External library

    Manual error handling

    Better error handling

    Basic features

    Advanced features

Next