📄Assignments Of Class 18: Error Handling and Loading States

Rashmi Mishra
0

 ðŸ“„Assignments  Of Class 18
Error Handling and Loading States


✅ Assignment 1: Add Loading State to User Fetch App

Task: Add a loading message ("Loading users...") while user data is being fetched.

✅ Solution:

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

useEffect(() => {

  const fetchUsers = async () => {

    setIsLoading(true);

    const res = await fetch("https://jsonplaceholder.typicode.com/users");

    const data = await res.json();

    setUsers(data);

    setIsLoading(false);

  };

  fetchUsers();

}, []);

 

return (

  <div>

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

    {!isLoading && users.map(user => <p key={user.id}>{user.name}</p>)}

  </div>

);


✅ Assignment 2: Add Basic Error Handling Using try-catch

Task: Use a try-catch block to handle any fetch errors.

✅ Solution:

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

const fetchUsers = async () => {

  try {

    const res = await fetch("https://jsonplaceholder.typicode.com/invalid-url");

    if (!res.ok) throw new Error("Failed to fetch users");

    const data = await res.json();

    setUsers(data);

  } catch (err) {

    setError(err.message);

  }

};

 

useEffect(() => {

  fetchUsers();

}, []); 

return (

  <div>

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

  </div>

);


✅ Assignment 3: Display Both Loading and Error State

Task: Show a loading message while fetching and display an error message if fetching fails.

✅ Solution:

return (

  <div>

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

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

    {!isLoading && !error && users.map(u => <p key={u.id}>{u.name}</p>)}

  </div>

);


✅ Assignment 4: Add a Retry Button on Error

Task: If there's an error, show a “Retry” button that re-runs the fetch function.

✅ Solution:

{error && (

  <div>

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

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

  </div>

)}


✅ Assignment 5: Simulate Delay for Loading State

Task: Simulate a 2-second delay before the data is shown to clearly visualize the loading state.

✅ Solution:

const fetchUsers = async () => {

  setIsLoading(true);

  try {

    await new Promise(resolve => setTimeout(resolve, 2000)); // Simulated delay

    const res = await fetch("https://jsonplaceholder.typicode.com/users");

    const data = await res.json();

    setUsers(data);

    setError(null);

  } catch (err) {

    setError("Could not load data");

  } finally {

    setIsLoading(false);

  }

};


✅ Assignment 6: Show "No Users Found" if Empty Data

Task: If the API returns an empty list, show "No Users Found".

✅ Solution:

return (

  <div>

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

    {error && <p>{error}</p>}

    {!isLoading && !error && users.length === 0 && <p>No Users Found</p>}

    {!isLoading && !error && users.map(user => <p key={user.id}>{user.name}</p>)}

  </div>

);


✅ Assignment 7: Log Detailed Error to Console, Show Friendly Message

Task: Log full error in console, but show user-friendly message on UI.

✅ Solution:

try {

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

  if (!res.ok) throw new Error("Server response not ok");

  const data = await res.json();

  setUsers(data);

} catch (err) {

  console.error("Full Error:", err); // Developer logs

  setError("Something went wrong. Please try again."); // User message

}


✅ Assignment 8: Disable Button During Loading

Task: Add a “Load Users” button. Disable it while loading is in progress.

✅ Solution:

<button onClick={fetchUsers} disabled={isLoading}>

  {isLoading ? "Loading..." : "Load Users"}

</button>


✅ Assignment 9: Display Spinner Instead of Text During Loading

Task: Use an animated spinner (e.g., "⏳") instead of text during loading.

✅ Solution:

{isLoading && <p> Please wait...</p>}

You can also use Bootstrap spinner:

{isLoading && <div className="spinner-border text-primary" role="status"></div>}


✅ Assignment 10: Show Different Messages Based on HTTP Status

Task: Show different messages for 404, 500, or unknown errors.

✅ Solution:

try {

  const res = await fetch("https://jsonplaceholder.typicode.com/invalid-url");

  if (!res.ok) {

    if (res.status === 404) {

      throw new Error("Data not found (404)");

    } else if (res.status === 500) {

      throw new Error("Server error (500)");

    } else {

      throw new Error("Unexpected error");

    }

  }

  const data = await res.json();

  setUsers(data);

} catch (err) {

  setError(err.message);

}


📌 Bonus Tips for Students:

  • Always wrap your async calls in try-catch.
  • Use finally to reset the loading state.
  • Make sure the UI gives clear feedback to the user.
  • Keep UI messages user-friendly, not technical.

Post a Comment

0Comments

Post a Comment (0)