💻Lecture Notes Of Class 18: Error Handling and Loading States

Rashmi Mishra
0

 💻Lecture Notes Of Class 18

 Error Handling and Loading States

🕒 Duration: 1 Hour

📘 Prerequisites: Basic knowledge of fetch, React state, and useEffect.


🔰 Objective

By the end of this class, students will be able to:

  • Understand the importance of error and loading state handling.
  • Use try-catch for error handling in async operations.
  • Use boolean states like isLoading and error to give user feedback.
  • Apply these concepts in a React app that fetches user data.

🧠 Topics Covered

1. ✅ Why Handle Loading and Errors?

Problem:
When we fetch data from an API, it takes time or might fail.

Scenarios:

  • Slow Internet → No feedback? User thinks app is frozen.
  • Server down → No error message? User doesn’t know what’s wrong.

Solution: Show clear loading and error messages!


2. 🔄 The Three Main States of API Calls

1.   Loading → When the API is fetching.

2.   Success → When data is fetched successfully.

3.   Error → When something goes wrong.


3. 🧪 try-catch Block

Used to catch errors during asynchronous operations like API calls.

try {

   // code that might throw error

} catch (error) {

   // handle the error here

}


4. 🧮 isLoading and error State in React

Let’s assume we’re using a React component:

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

function UserComponent() {

  const [users, setUsers] = useState([]);

  const [isLoading, setIsLoading] = useState(false);

  const [error, setError] = useState(null); 

  useEffect(() => {

    const fetchUsers = async () => {

      setIsLoading(true);        // Start loading

      setError(null);            // Reset previous errors     

      try {

        const res = await fetch("https://api.example.com/users");

        if (!res.ok) {

          throw new Error("Something went wrong!");

        }

        const data = await res.json();

        setUsers(data);

      } catch (err) {

        setError(err.message);   // Capture error

      } finally {

        setIsLoading(false);     // End loading

      }

    };

 

    fetchUsers();

  }, []);

 

  return (

    <div>

      <h1>Users</h1>

      {isLoading && <p>Loading...</p>}

      {error && <p style={{ color: 'red' }}>Error: {error}</p>}

      {!isLoading && !error && users.map((user) => (

        <div key={user.id}>{user.name}</div>

      ))}

    </div>

  );

} 

export default UserComponent;


5. ✅ Explanation of Code

Part

Description

isLoading

Becomes true while data is loading. Used to show a loading spinner or message.

error

Stores the error message if something fails.

try { ... } catch {}

Handles any runtime errors from the fetch.

finally

Runs after try/catch — turns off loading in both success and error.


🔧 6. Common Mistakes

  • ❌ Not resetting error before new fetch.
  • ❌ Not setting isLoading to false in finally.
  • ❌ Forgetting to show fallback UI when error happens.

🏃‍♂️ Activity – Add Loading and Error Messages

🔨 Modify your "Fetch User Data" App

1.   Add two new useState() hooks:

const [isLoading, setIsLoading] = useState(false);

const [error, setError] = useState(null);

2.   Wrap fetch() inside try-catch-finally.

3.   Show <p>Loading...</p> if loading.

4.   Show <p>Error: {error}</p> if error.

🎯 Goal: Your app should now clearly show:

  • A loading message while fetching.
  • An error message if the API fails.

🎒 Homework

💡 Add a "Retry" Button

When there’s an error:

  • Show a Retry button.
  • On click, re-run the API fetch.

{error && (

  <div>

    <p>Error: {error}</p>

    <button onClick={fetchUsers}>Retry</button>

  </div>

)}

Make sure fetchUsers is moved outside useEffect so it can be reused:

const fetchUsers = async () => {

  // same code

};

useEffect(() => {

  fetchUsers();

}, []);


📚 Summary

Concept

Explanation

try-catch

Used to handle any error in async calls

isLoading

Boolean flag to show/hide loading UI

error

Stores error messages for display

Retry mechanism

Improves UX by letting users try again


❓ Q&A (Last 10 Minutes)

  • What happens if we don’t use finally?
  • Can we show a spinner instead of text in loading?
  • Should we always show error messages to users?

📌 Additional Tips

  • You can show loading using spinners from libraries like Bootstrap or Material UI.
  • You can log error details to the console and show a user-friendly message to users.
  • Using useReducer is a good alternative in more complex apps.
Tags

Post a Comment

0Comments

Post a Comment (0)