Robust Data Fetching
Mission
Fetch data from an API with useEffect and async/await, handling the three states every request has: loading, error and success.
Tasks
- 1
Declare three states:
data,loading(boolean) anderror. - 2
Create an async function inside
useEffectthat callsfetch. - 3
Wrap it in
try/catch/finallyto handle network and API failures. - 4
Throw when the response is not ok, because
fetchdoes not do it for you. - 5
Render each state: a loading message, the error message, or the list of results.
import React, { useState, useEffect } from 'react'; export default function RobustFetching() { // 1. Declare your 3 states here: data, loading and error useEffect(() => { // 2. Create your async function for the fetch // Suggested API: https://rickandmortyapi.com/api/character }, []); return ( <div style={{ padding: '20px', fontFamily: 'sans-serif', textAlign: 'center' }}> <h1>Rick & Morty Characters</h1> {/* 3. Conditional rendering: - If loading is true, show a loading message. - If there is an error, show it in red. - If there is data, use .map() to show the names. */} </div> ); }
Requirements
0/9Declares data, loading and error states (not run yet)
Calls fetch inside useEffect (not run yet)
useEffect has an empty dependency array (not run yet)
Uses async/await inside a try/catch (not run yet)
Treats a non-ok response as an error (res.ok + throw) (not run yet)
Turns loading off inside `finally` (not run yet)
Renders the loading state (not run yet)
Shows the error to the user (not run yet)
Renders the results with .map() (not run yet)
AI mentor
Reviews only the files you changed, plus the checks you missed.
Run the checks first. They are free and instant.