EthicsComputerCourses
Join training +91 90532 10052

Fetching Data from Your API

MERN Stack · Lesson 10 of 20 Intermediate 11 min read Updated

By the end of this lesson the TaskBoard board will show real tasks from MongoDB instead of sample data. You will write one small function that makes every HTTP request, turn the API's error shape into JavaScript errors, load tasks in a custom hook that cancels stale requests, and move cards between columns with an optimistic update that rolls back if the server says no.

What you should know first: React Front End with Vite for the client files, and Authentication with JWT & Cookies, because the task routes now need a login cookie. On the React side, see useEffect & Side Effects, Custom Hooks and Data Fetching Patterns; for fetch itself, see Fetch API. Versions checked: React 19.3.1 and Vite 8.3.8 in Chrome, against the API from the earlier lessons. Every result below was seen in a real browser session.

The path of one request

When BoardPage asks for tasks, the request travels like a parcel through a courier hub:

  1. React calls fetch("/api/tasks"). The browser sends it to its own origin, http://localhost:5173, and attaches the token cookie, because the cookie's path /api matches.
  2. The Vite dev server sees the /api prefix and forwards the request, cookie included, to Express on port 4000.
  3. Express runs requireAuth, the controller and Mongoose, and replies with JSON.
  4. Vite passes the reply back. As far as the browser knows, one server answered.

Because the browser only ever talks to one origin, CORS does not get involved in development. In production you can keep that setup by serving the client and API from one domain. If the API lives elsewhere, set VITE_API_URL; the cors allow-list with credentials: true from Build a REST API with Express 5 is ready for that case.

Step 1: One function for every request

fetch has a surprise for beginners: it only rejects when the network fails. A 404 or 500 reply still resolves successfully, so code that skips the status check happily treats an error body as data. Wrap fetch once and never think about it again. Create client/src/api/client.js:

JavaScript
// The only file that calls fetch(). Every request in the app goes through apiRequest().
const BASE_URL = import.meta.env.VITE_API_URL ?? "";

export class ApiError extends Error {
  constructor(status, message, details = []) {
    super(message);
    this.name = "ApiError";
    this.status = status;
    this.details = details;
  }
}

export async function apiRequest(path, { method = "GET", body, signal } = {}) {
  let res;
  try {
    res = await fetch(BASE_URL + path, {
      method,
      signal,
      credentials: "include",
      headers: body === undefined ? {} : { "Content-Type": "application/json" },
      body: body === undefined ? undefined : JSON.stringify(body),
    });
  } catch (err) {
    if (err.name === "AbortError") throw err;
    throw new ApiError(0, "Cannot reach the server. Check your connection and try again.");
  }
  if (res.status === 204) return null;
  const data = await res.json().catch(() => null);
  if (!res.ok) {
    throw new ApiError(res.status, data?.error?.message ?? `Request failed (${res.status})`, data?.error?.details);
  }
  return data;
}

Here is what each part handles:

  • credentials: "include" sends cookies even when VITE_API_URL points to another origin. On the same origin, fetch sends them anyway.
  • AbortError is passed through untouched, because a cancelled request is not a failure to show the user.
  • 204 has no body, so DELETE returns null instead of crashing in res.json().
  • A reply that is not JSON gives data = null and a fallback message. This really happens: with Express stopped, the Vite proxy itself answered 502 Bad Gateway with a plain-text body.
  • ApiError carries status and details, so screens can tell "please log in" (401) from "you cannot do that" (403) and show field messages next to inputs.

Step 2: One function per endpoint

Delete client/src/api/sampleTasks.js and create client/src/api/tasks.js. Each function is named after what it does, so components never build URLs:

JavaScript
import { apiRequest } from "./client.js";

// One function per endpoint, named after what it does, not how.
export function getTasks({ status, signal } = {}) {
  const query = new URLSearchParams();
  if (status) query.set("status", status);
  return apiRequest(`/api/tasks${query.size ? `?${query}` : ""}`, { signal });
}

export function createTask(task) {
  return apiRequest("/api/tasks", { method: "POST", body: task });
}

export function updateTask(id, changes) {
  return apiRequest(`/api/tasks/${id}`, { method: "PATCH", body: changes });
}

export function deleteTask(id) {
  return apiRequest(`/api/tasks/${id}`, { method: "DELETE" });
}

URLSearchParams encodes values safely, so a status with odd characters can never break the URL. createTask and deleteTask are not used yet; Forms, Validation & Errors builds the form that calls createTask.

Step 3: Log in for now

The task routes answer 401 without a login cookie. The proper login page arrives in Login, Protected Routes & Sessions. Until then, seed the database, start both halves with npm run dev, open http://localhost:5173, and run this in the browser's DevTools console:

JavaScript
await fetch("/api/auth/login", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({ email: "priya@example.com", password: "rohtak-chalk-2026" }),
}).then((res) => res.status);
Output
200

Now type document.cookie in the same console. It returns "", an empty string. The browser stored the token, but because it is HttpOnly, page JavaScript cannot see it. That is the protection from the last lesson, working in a real browser.

Step 4: A useTasks hook

A custom hook is a function whose name starts with use and which calls other hooks. It lets BoardPage say what it needs ("the tasks") while the hook handles how. Create client/src/hooks/useTasks.js:

JavaScript
import { useCallback, useEffect, useState } from "react";
import { getTasks } from "../api/tasks.js";

// Loads tasks (optionally of one status) and loads again when the status changes or reload() is called.
export function useTasks(status) {
  const [reloadCount, setReloadCount] = useState(0);
  const [result, setResult] = useState({ key: null, tasks: [], error: null });
  const key = `${status ?? "all"}:${reloadCount}`; // names the request the screen needs now

  useEffect(() => {
    const controller = new AbortController();
    getTasks({ status, signal: controller.signal })
      .then((tasks) => setResult({ key, tasks, error: null }))
      .catch((error) => {
        if (error.name !== "AbortError") setResult({ key, tasks: [], error });
      });
    return () => controller.abort(); // runs when status changes or the component goes away
  }, [key, status]);

  const setTasks = useCallback((update) => setResult((r) => ({ ...r, tasks: update(r.tasks) })), []);
  const reload = useCallback(() => setReloadCount((n) => n + 1), []);

  return { tasks: result.tasks, error: result.error, loading: result.key !== key, setTasks, reload };
}

Three ideas make this hook reliable:

  • Cancel what you no longer need. An AbortController can cancel a fetch. The effect's clean-up function aborts the old request whenever status changes or the page closes. Without it, a slow old reply could arrive after a fast new one and overwrite it. The first example below shows that bug happening.
  • loading is derived, not stored. Each result remembers which request (key) it belongs to. If the screen needs a different key than the one on hand, we are loading. Our first version set loading to true inside the effect, and oxlint warned react(set-state-in-effect): Calling setState synchronously within an effect can trigger cascading renders. Deriving it removes the extra render and the warning.
  • StrictMode runs the effect twice in development. React mounts, cleans up and mounts again to check the clean-up works. With the abort in place this is harmless. In our session the API log showed it before login: two GET /api/tasks 401 lines for one page load, one from each mount.

Step 5: The board with real data

Give the cards a way to move. TaskCard.jsx gets an onMove prop and one button per other status:

React JSX
import { formatDueDate, isOverdue } from "../utils/dates.js";

const LABELS = { todo: "To do", doing: "Doing", done: "Done" };

export default function TaskCard({ task, onMove }) {
  const overdue = isOverdue(task);
  return (
    <article className={overdue ? "card overdue" : "card"}>
      <h3>{task.title}</h3>
      <p>
        {formatDueDate(task.dueDate)}
        {overdue && " (overdue)"} · {task.assignee?.name ?? "Unassigned"}
      </p>
      {Object.keys(LABELS)
        .filter((status) => status !== task.status)
        .map((status) => (
          <button key={status} type="button" onClick={() => onMove(task, status)}>
            Move to {LABELS[status]}
          </button>
        ))}
    </article>
  );
}

In TaskColumn.jsx, accept onMove as a prop and pass it on: <TaskCard key={task.id} task={task} onMove={onMove} />. Then rewrite pages/BoardPage.jsx:

React JSX
import { useState } from "react";
import TaskColumn from "../components/TaskColumn.jsx";
import { updateTask } from "../api/tasks.js";
import { useTasks } from "../hooks/useTasks.js";

const COLUMNS = [
  { status: "todo", title: "To do" },
  { status: "doing", title: "Doing" },
  { status: "done", title: "Done" },
];

export default function BoardPage() {
  const { tasks, setTasks, loading, error, reload } = useTasks();
  const [notice, setNotice] = useState("");

  async function moveTask(task, status) {
    setNotice("");
    setTasks((list) => list.map((t) => (t.id === task.id ? { ...t, status } : t))); // optimistic
    try {
      const saved = await updateTask(task.id, { status });
      setTasks((list) => list.map((t) => (t.id === saved.id ? saved : t)));
    } catch (err) {
      setTasks((list) => list.map((t) => (t.id === task.id ? task : t))); // roll back
      setNotice(err.message);
    }
  }

  if (loading) return <p>Loading tasks...</p>;
  if (error?.status === 401) return <p>Please log in to see the board.</p>;
  if (error) {
    return (
      <p role="alert">
        Could not load tasks: {error.message} <button onClick={reload}>Try again</button>
      </p>
    );
  }

  const byStatus = Object.groupBy(tasks, (task) => task.status);
  return (
    <>
      {notice && <p role="alert">{notice}</p>}
      <div className="board">
        {COLUMNS.map((col) => (
          <TaskColumn key={col.status} title={col.title} tasks={byStatus[col.status] ?? []} onMove={moveTask} />
        ))}
      </div>
    </>
  );
}

An optimistic update changes the screen first and asks the server second, like a waiter who writes "paid" as soon as you hand over the card and corrects it only if the machine declines. It makes the board feel instant. When the server replies, the saved task replaces the guess, so updatedAt and any server-side changes appear. If the server refuses, only that one card goes back to how it was.

Here is what the browser showed, signed in as Priya, in four situations:

Output
Before logging in:
  Please log in to see the board.

After logging in (each card also shows its two "Move to" buttons):
  To do (1)   Print Class 10 maths worksheets   20 Nov · Priya Sharma
  Doing (1)   Call parents about Sunday test    18 Nov · Kabir Malik
  Done (1)    Update physics batch timings      12 Nov · Unassigned

"Move to Done" on Kabir's card: it jumped to Done, then came back, with
  You can only change tasks assigned to you

With Express stopped:
  Could not load tasks: Request failed (502) Try again

The 403 message came straight from the server's HttpError, through ApiError, to the screen, without a single special case in between. The 502 is the Vite proxy's reply when nothing is listening on port 4000.

See the race and the rollback

The first example fakes a server whose "To do" reply is slow. Turn the abort off, choose "todo" and then quickly "doing": the slow reply arrives last and the list no longer matches the filter. Turn the abort back on and repeat; the old request is cancelled.

React JSXOpen in editor
import { useEffect, useState } from "react";
import { createRoot } from "react-dom/client";

const ALL = [
  { id: "t1", title: "Print Class 10 maths worksheets", status: "todo" },
  { id: "t2", title: "Call parents about Sunday test", status: "doing" },
  { id: "t3", title: "Update physics batch timings", status: "done" },
];
const DELAY = { all: 400, todo: 1500, doing: 300, done: 600 }; // the "todo" reply is slow

function fakeGetTasks(status, signal, log) {
  return new Promise((resolve, reject) => {
    log(`start ${status}`);
    let replied = false;
    const timer = setTimeout(() => {
      replied = true;
      log(`reply ${status}`);
      resolve(status === "all" ? ALL : ALL.filter((t) => t.status === status));
    }, DELAY[status]);
    signal.addEventListener("abort", () => {
      if (replied) return; // too late to cancel: the reply already arrived
      clearTimeout(timer);
      log(`abort ${status}`);
      reject(new DOMException("Aborted", "AbortError"));
    });
  });
}

function RaceDemo() {
  const [status, setStatus] = useState("all");
  const [useAbort, setUseAbort] = useState(true);
  const [tasks, setTasks] = useState([]);
  const [log, setLog] = useState([]);

  useEffect(() => {
    const controller = new AbortController();
    const add = (line) => setLog((l) => [...l.slice(-5), line]);
    fakeGetTasks(status, controller.signal, add)
      .then(setTasks)
      .catch((err) => { if (err.name !== "AbortError") console.error(err); });
    return () => { if (useAbort) controller.abort(); };
  }, [status, useAbort]);

  const wrong = tasks.some((t) => status !== "all" && t.status !== status);
  return (
    <div>
      <label>Filter <select value={status} onChange={(e) => setStatus(e.target.value)}>
        <option>all</option><option>todo</option><option>doing</option><option>done</option>
      </select></label>{" "}
      <label><input type="checkbox" checked={useAbort} onChange={(e) => setUseAbort(e.target.checked)} /> abort old requests</label>
      <ul>{tasks.map((t) => <li key={t.id}>{t.title} ({t.status})</li>)}</ul>
      <p style={{ color: wrong ? "crimson" : "green" }}>{wrong ? "Stale data: the list does not match the filter!" : "List matches the filter."}</p>
      <pre>{log.join("\n")}</pre>
    </div>
  );
}

createRoot(document.getElementById("root")).render(<RaceDemo />);

With the abort on, the log reads start todo, abort todo, start doing, reply doing. With it off, it reads start todo, start doing, reply doing, reply todo, and the page turns red.

The second example shows the optimistic move with rollback. Its fake server accepts moves only for Priya's own tasks, like the real API does for a teacher:

React JSXOpen in editor
import { useState } from "react";
import { createRoot } from "react-dom/client";

const me = "Priya Sharma";
const start = [
  { id: "t1", title: "Print Class 10 maths worksheets", status: "todo", assignee: "Priya Sharma" },
  { id: "t2", title: "Call parents about Sunday test", status: "doing", assignee: "Kabir Malik" },
];

// Fake PATCH: 403 unless the task is assigned to me, after 700 ms.
function fakeUpdate(task, status) {
  return new Promise((resolve, reject) => setTimeout(() => {
    if (task.assignee !== me) reject(new Error("You can only change tasks assigned to you"));
    else resolve({ ...task, status });
  }, 700));
}

function MoveDemo() {
  const [tasks, setTasks] = useState(start);
  const [notice, setNotice] = useState("");

  async function move(task, status) {
    setNotice("");
    setTasks((list) => list.map((t) => (t.id === task.id ? { ...t, status } : t)));
    try {
      const saved = await fakeUpdate(task, status);
      setTasks((list) => list.map((t) => (t.id === saved.id ? saved : t)));
      setNotice(`Saved: ${saved.title} is now ${saved.status}`);
    } catch (err) {
      setTasks((list) => list.map((t) => (t.id === task.id ? task : t)));
      setNotice(err.message);
    }
  }

  return (
    <div>
      {tasks.map((t) => (
        <p key={t.id}>
          <strong>{t.status.toUpperCase()}</strong> {t.title} ({t.assignee}){" "}
          <button onClick={() => move(t, "done")} disabled={t.status === "done"}>Move to done</button>
        </p>
      ))}
      <p role="alert">{notice}</p>
    </div>
  );
}

createRoot(document.getElementById("root")).render(<MoveDemo />);

Click "Move to done" on Kabir's task: it shows DONE at once, then returns to DOING with the 403 message. Priya's task stays DONE and the page says "Saved: Print Class 10 maths worksheets is now done".

Common mistakes

  • Treating every resolved fetch as success. Check res.ok, or 404 and 500 bodies end up in your state.
  • Calling fetch in many components. URLs, headers and error handling drift apart. Keep one apiRequest.
  • No clean-up in data effects. Slow old replies overwrite new ones, and closed pages try to update state.
  • Showing AbortError to users. A cancelled request is normal; ignore it.
  • Forgetting the rollback. An optimistic update without a catch leaves the screen showing something the database never stored.
  • Reading the JWT in React. You cannot, and should not; ask GET /api/auth/me who is logged in.

Interview questions

1. Does fetch reject on a 404 or 500 response?

No. fetch rejects only when the request cannot complete, for example a network failure, a CORS block or an abort. HTTP error statuses resolve normally, so you must check res.ok or res.status and throw your own error.

2. Why use an AbortController in a data-fetching effect?

It cancels requests the component no longer needs, when the inputs change or the component unmounts. That prevents race conditions where a slower, older response overwrites a newer one, and avoids wasted work. The effect's clean-up function calls abort().

3. What is an optimistic update, and what must you add to make it safe?

The UI shows the expected result before the server confirms it, which makes the app feel instant. You must keep the old value and roll back if the request fails, and replace the guess with the server's reply when it succeeds.

4. How does the browser send an HttpOnly cookie to the API if JavaScript cannot read it?

The browser attaches cookies itself to matching requests; page scripts never touch them. On the same origin this happens by default. For another origin, fetch needs credentials: "include" and the server must allow that exact origin with Access-Control-Allow-Credentials: true.

Key points

  • api/client.js holds the one apiRequest() that checks res.ok, handles 204 and non-JSON bodies, and throws ApiError with status and details.
  • api/tasks.js has one function per endpoint; components never build URLs.
  • useTasks loads data in an effect, aborts stale requests in the clean-up, and derives loading instead of storing it.
  • StrictMode runs effects twice in development; correct clean-up makes that harmless.
  • Optimistic updates change the screen first, then replace the guess with the server's reply or roll back on error.
  • Until the login page exists, sign in from the DevTools console; the HttpOnly cookie stays invisible to document.cookie.

Exercise

Add a "Show" drop-down above the board with the options All, To do, Doing and Done. Keep the choice in BoardPage state and pass it to useTasks(status), so the server filters the list (pass undefined for All). The drop-down must stay on screen while a request is loading. Watch the Network tab: each change should make one request such as /api/tasks?status=doing, and a quick second change should cancel the first.

Show solution
React JSX
// pages/BoardPage.jsx: new state at the top of the component
const [show, setShow] = useState("");
const { tasks, setTasks, loading, error, reload } = useTasks(show || undefined);

// Replace the early returns with one "content" variable, so the drop-down always renders.
let content;
if (loading) {
  content = <p>Loading tasks...</p>;
} else if (error?.status === 401) {
  content = <p>Please log in to see the board.</p>;
} else if (error) {
  content = (
    <p role="alert">
      Could not load tasks: {error.message} <button onClick={reload}>Try again</button>
    </p>
  );
} else {
  const byStatus = Object.groupBy(tasks, (task) => task.status);
  content = (
    <div className="board">
      {COLUMNS.map((col) => (
        <TaskColumn key={col.status} title={col.title} tasks={byStatus[col.status] ?? []} onMove={moveTask} />
      ))}
    </div>
  );
}

return (
  <>
    <label>
      Show{" "}
      <select value={show} onChange={(e) => setShow(e.target.value)}>
        <option value="">All</option>
        <option value="todo">To do</option>
        <option value="doing">Doing</option>
        <option value="done">Done</option>
      </select>
    </label>
    {notice && <p role="alert">{notice}</p>}
    {content}
  </>
);
Output
API log after choosing "Doing" and then, at once, "Done":
19a7bc42 GET /api/tasks?status=doing 200 28.1ms
4c6c5e63 GET /api/tasks?status=done 200 18.3ms
Browser: only the ?status=done reply was used; the board shows Done (1) with "Update physics batch timings".

useTasks already lists status in its effect dependencies, so each choice starts a new request and the clean-up aborts the previous one. The "doing" request still reached the server, but the browser dropped its reply, so it could never overwrite the "done" list.

Quick Quiz

1. fetch("/api/tasks") gets a 401 reply. What does the promise from fetch do?

2. Why does useTasks return a clean-up function that calls controller.abort()?

3. In moveTask, what happens when the server replies 403?

4. What does document.cookie return after logging in to TaskBoard?

Learn MERN Stack with a mentor

Free lessons get you started. Our Full Stack Web Development training adds real projects and code reviews from working developers.

  • Project-based learning
  • Mentor code reviews
  • Free counselling call