💻Lecture Notes Of Class 17: Fetching Data from API in React

Rashmi Mishra
0

 💻Lecture Notes Of Class 17

 Fetching Data from API in React


Objective:

  • Learn how to use the fetch() function to call APIs.
  • Use useEffect to make API calls when a component loads.
  • Manage API data and loading state with useState.
  • Practice fetching and displaying user data from an open API.

Introduction to APIs (10 minutes)

What is an API?

  • API stands for Application Programming Interface.
  • It is a way for different software applications to communicate with each other.
  • Web APIs allow us to get data from remote servers over the internet.

Example:

  • When you check the weather app, it fetches data from a weather API.
  • In our case, we'll fetch user data from a sample API endpoint:
    https://jsonplaceholder.typicode.com/users

How to Fetch Data in React (20 minutes)

1. The fetch() Function:

  • fetch() is a built-in JavaScript function used to make HTTP requests.
  • It returns a Promise that resolves to a Response object.

Basic usage:

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

  .then(response => response.json())  // Convert response to JSON

  .then(data => console.log(data))    // Use the data

  .catch(error => console.error('Error:', error));

2. Using useEffect for Side Effects:

  • React components re-render many times.
  • To run code only once (like fetching data when the component loads), we use useEffect.
  • useEffect runs after the component renders.

Syntax:

useEffect(() => {

  // code here runs once when the component mounts

}, []);  // empty dependency array means run once only

3. Managing State with useState:

  • We need state variables to hold:
    • The data fetched from the API.
    • The loading status (whether the fetch is in progress).

Example:

const [users, setUsers] = useState([]);       // for data

const [loading, setLoading] = useState(true); // for loading status


Putting It All Together (20 minutes)

Full Example: Fetch and Display Users

import React, { useEffect, useState } from 'react'; 

function UserList() {

  const [users, setUsers] = useState([]);       // to store user data

  const [loading, setLoading] = useState(true); // to show loading state 

  useEffect(() => {

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

      .then(response => response.json())     // parse JSON response

      .then(data => {

        setUsers(data);                       // set users state

        setLoading(false);                    // loading complete

      })

      .catch(error => {

        console.error('Error fetching data:', error);

        setLoading(false);

      });

  }, []); 

  if (loading) {

    return <p>Loading users...</p>;

  } 

  return (

    <div>

      <h2>User List</h2>

      <ul>

        {users.map(user => (

          <li key={user.id}>

            {user.name} ({user.email})

          </li>

        ))}

      </ul>

    </div>

  );

} 

export default UserList;

Explanation:

  • We declare users and loading state variables.
  • In useEffect, we call fetch() to get user data.
  • When the data arrives, we update users and change loading to false.
  • If loading is true, we show a loading message.
  • Once data is ready, we display it in a list.

Activity (10 minutes)

Task:

  • Create a React component that fetches user data from https://jsonplaceholder.typicode.com/users.
  • Display the user names and emails in a simple list like above.

Homework

Challenge:

  • Style the displayed users into cards instead of a list.
  • Each card should show the user’s:
    • Name
    • Email
    • Address (street, city)
    • Phone number

Additional Notes:

  • Always handle errors when fetching data.
  • You can add a refresh button to fetch data again.
  • Explore other APIs for practice.
  • Use CSS to make data visually appealing.

Summary

  • API allows us to get data from the web.
  • Use fetch() inside useEffect to get data when component loads.
  • Manage data and loading status with useState.
  • Practice fetching and displaying user data.
Tags

Post a Comment

0Comments

Post a Comment (0)