React Tutorial 0/120 lessons ~6 min read Lesson 53

    Fetch API

    Fetch API covers GET and POST JSON requests, response.ok checks, AbortController cancellation, response body parsing, and async bugs.

    Course progress0%
    Focus
    10 guided sections
    Practice signal
    Examples included
    Career prep
    Interview Q&A included

    Course: React — Routing & API Integration Lesson: 08

    Learning objectives

    Use the browser Fetch API for GET and POST requests, parse JSON safely, handle HTTP failures, cancel requests, and avoid common asynchronous bugs.

    Basic GET request

    fetch() returns a Promise that resolves to a Response. An HTTP error status such as 404 does not normally reject the Promise; inspect response.ok or response.status.

    javascript
    async function getProducts() {
    const response = await fetch("/api/products");
    if (!response.ok) {
    throw new Error(`Request failed with status ${response.status}`);
    }
    return response.json();
    }

    POST JSON data

    javascript
    async function createProduct(product) {
    const response = await fetch("/api/products", {
    method: "POST",
    headers: {
    "Content-Type": "application/json",
    "Accept": "application/json"
    },
    body: JSON.stringify(product)
    });
    if (!response.ok) {
    const message = await response.text();
    throw new Error(message || "Unable to create product");
    }
    if (response.status === 204) return null;
    return response.json();
    }

    JSON.stringify converts a JavaScript value into a JSON request body. The Content-Type header tells the server how to interpret it.

    Use Fetch inside an Effect carefully

    javascript
    useEffect(() => {
    const controller = new AbortController();
    async function load() {
    try {
    setStatus("loading");
    const response = await fetch("/api/products", {
    signal: controller.signal
    });
    if (!response.ok) throw new Error("Could not load products");
    setProducts(await response.json());
    setStatus("success");
    } catch (error) {
    if (error.name !== "AbortError") {
    setError(error);
    setStatus("error");
    }
    }
    }
    load();
    return () => controller.abort();
    }, []);

    An AbortController helps stop a request when the component no longer needs its result. For changing identifiers or search terms, include the relevant dependency and cancel the previous request during cleanup.

    Handle response bodies once

    A response body is a stream and should generally be consumed once. Choose json(), text(), blob(), or another parser according to the endpoint contract. Do not call response.json() and then expect to read the same body again as text.

    Error categories

    Distinguish network errors, HTTP errors, parsing errors, cancellation, and application-level validation errors. These have different causes and may require different user messages or retry behavior.

    Common mistakes

    • Not checking response.ok.
    • Calling response.json() for a 204 response.
    • Forgetting JSON.stringify for JSON request bodies.
    • Treating an aborted request as a user-visible failure.
    • Updating state from a request that is no longer relevant.
    • Logging sensitive request headers or payloads.

    Best practices

    Wrap repeated request behavior in service functions, use AbortController, validate response data, and expose clear loading/error/success states. For complex caching and synchronization, evaluate a dedicated server-state library rather than rebuilding all behavior manually.

    Interview questions & answers

    Interview preparation

    5 questions grouped by difficulty — expand any card for a model answer and follow-up probe.

    Beginner

    2
    1. 1What does fetch return?
      Beginner

      Model answer

      A Promise that resolves to a Response object describing status, headers, and a readable body stream.
    2. 2What is AbortController?
      Beginner

      Model answer

      A browser API that lets you abort an in-flight fetch via signal, typically in Effect cleanup when the request is no longer needed.

    Intermediate

    2
    1. 3Why does a 404 not automatically reject a Fetch Promise?
      Intermediate

      Model answer

      Fetch only rejects for network failures. HTTP error statuses still resolve, so application code must inspect response.ok.
    2. 4How should a 204 response be handled?
      Intermediate

      Model answer

      Treat success with no body—do not call response.json(); return null or skip parsing.

    Advanced

    1
    1. 5How do you send JSON in a POST request?
      Advanced

      Model answer

      Set method: "POST", Content-Type: application/json, and body: JSON.stringify(payload), then check the response.

    Practice

    Build a product search request with a query parameter. Cancel the previous request when the user changes the search term and display loading, empty, error, and result states.

    Ready to mark this lesson complete?Track your journey across the entire course.