React
/Beginner
Fetch API
Definition
The native browser API for making HTTP requests to servers to retrieve or save data.
Explain Like I'm New
Fetch is like a mail carrier built right into the browser. You give it an address (URL), and it goes out to the internet, picks up the package (JSON data), and brings it back to your React component.
Real World Example
Fetching a list of users from `https://jsonplaceholder.typicode.com/users` when a component mounts, and storing that array in a `useState` hook to map over and display.
Common Use Cases
- •Retrieving data from a backend REST API
- •Sending form data via POST requests
Interactive Example
import React, { useState, useEffect } from "react"; export default function FetchDemo() { const [data, setData] = useState([]); const [loading, setLoading] = useState(true); const [error, setError] = useState(null); useEffect(() => { fetch("https://jsonplaceholder.typicode.com/users") .then(res => { if (!res.ok) throw new Error("Server responded with " + res.status); return res.json(); // Returns another promise! }) .then(json => { setData(json); setLoading(false); }) .catch(err => { setError(err.message); setLoading(false); }); }, []); if (loading) return <div>Loading...</div>; if (error) return <div className="text-red-500">Error: {error}</div>; return ( <ul className="p-4 border"> {data.map(user => <li key={user.id}>{user.name}</li>)} </ul> ); }
Interview Questions
basic
- Is Fetch specific to React?
- Does `fetch()` return data immediately?
intermediate
- Why do you have to call `.json()` on a fetch response?
- Does `fetch` throw an error if the server returns a 404 or 500?
advanced
- How do you abort a fetch request if a component unmounts?
- Why does React 18 Strict Mode cause fetch in `useEffect` to run twice?
trick
- If the user's internet disconnects, does fetch throw an error or return a status code?