Lesson 36/100

Tutorials React.js Tutorial

Fetch API — Complete Guide

Fetch API — Complete Guide: free step-by-step lesson with examples, common mistakes, and interview tips — part of React.js Tutorial on Toolliyo Academy.

On this page

React.js Tutorial · Lesson 36 of 100

Fetch API

Beginner ✓IntermediateAdvancedProfessional

Intermediate · 2 — Build apps · ~14 min read · Module 4: Routing & Data

Introduction

You know the basics now. Here we use Fetch API in real app situations — forms, pages, and data. Still plain language, just a bit more depth. fetch sends HTTP requests from the browser. It returns a Promise. You call .json() on the response to parse JSON data. Almost every React app loads or saves data. fetch is built in — no install needed.

Routing is how a single React app feels like many pages. Users expect URLs like /cart and /checkout — Router makes that work.

When will you use this?

Add routing when your app has more than one screen and URLs should be bookmarkable.

  • Multi-page apps like dashboards use React Router — /settings, /profile, /orders.
  • E-commerce sites route /product/123 to a product detail component.

Real-world: load My Courses on Toolliyo

Student dashboard calls GET /api/enrollments on mount — native fetch, no extra library for simple JSON reads.

Production-style code

function MyCourses() {
  const [courses, setCourses] = useState([]);
  const [status, setStatus] = useState('loading');

  useEffect(() => {
    fetch('/api/enrollments', { credentials: 'include' })
      .then(r => {
        if (!r.ok) throw new Error(r.statusText);
        return r.json();
      })
      .then(data => { setCourses(data); setStatus('ready'); })
      .catch(() => setStatus('error'));
  }, []);

  if (status === 'loading') return <p>Loading courses…</p>;
  if (status === 'error') return <p>Could not load courses.</p>;
  return <CourseList courses={courses} />;
}

What happens in production: fetch is built into browsers — perfect for read-heavy LMS and catalog screens before adding axios interceptors.

Lesson example (start here)

Copy this smaller example first. Once it works, compare it with the real-world code above.

useEffect(() => {
  let cancelled = false;
  fetch('/api/products')
    .then(res => {
      if (!res.ok) throw new Error('Failed to load');
      return res.json();
    })
    .then(data => { if (!cancelled) setProducts(data); })
    .catch(err => setError(err.message));
  return () => { cancelled = true; };
}, []);

Line-by-line walkthrough

CodeWhat it means
useEffect(() => {Runs side effects — fetch data, timers, or subscriptions — after the screen updates.
let cancelled = false;Part of the Fetch API example — read it together with the lines before and after.
fetch('/api/products')Calls an API to load or save data from a server.
.then(res => {Defines a function — often a component or event handler.
if (!res.ok) throw new Error('Failed to load');Part of the Fetch API example — read it together with the lines before and after.
return res.json();Sends UI or a value back to whoever called this function.
})Closes a block started by { or ( above.
.then(data => { if (!cancelled) setProducts(data); })Defines a function — often a component or event handler.
.catch(err => setError(err.message));Defines a function — often a component or event handler.
return () => { cancelled = true; };Returns JSX — the HTML-like UI this component displays.
}, []);Closes a block started by { or ( above.

How it works (big picture)

  • res.ok is false for 404/500.
  • cancelled flag avoids setting state after unmount.
  • cleanup prevents memory leak warnings.

Do this on your computer

  1. fetch URL in useEffect or click handler.
  2. Check res.ok before parsing.
  3. Add loading and error UI states.
  4. Read the real-world section and name which part of the app uses this topic.
  5. Run the example locally and confirm the same behavior in the browser.
  6. Change one value in the example (text, initial state, or URL) and predict what will happen before you save.

Experiments — try changing this

  • Change text or labels in the example and save — watch the browser update.
  • Break the code on purpose (remove a bracket), read the error message, then fix it.
  • Open React DevTools (browser extension) while running Fetch API and inspect component props/state.

Remember

fetch → then json → setState. Handle errors and loading. Use cleanup or AbortController in effects.

Common questions

fetch vs axios?

fetch is built-in; axios adds interceptors and nicer defaults.

How long should I spend on Fetch API?

Until you can explain it in your own words and run the example without looking at the answer. Beginners often need 30–60 minutes per new hook or routing topic; setup lessons may take one afternoon.

What if I get stuck on Fetch API?

Re-read the line-by-line walkthrough, check the browser console for red errors, and compare your code character-by-character with the example. Search the exact error text — someone else had it too.

Where is Fetch API used in real jobs?

See the real-world section above — the same pattern appears in LMS, banking, e-commerce, and SaaS products. Interviewers ask you to explain it using one concrete example from your project or this lesson.

Interview prep for this lesson

Practice these questions aloud after reading—each links to a full structured answer.

Mid PDF Detailed
Example of mocking fetch in a test:?
Short answer: import { render, screen, waitFor } from '@testing-library/react'; import MyComponent from './MyComponent'; test('fetches and displays data', async () =&gt; { global.fetch = jest.fn(() =&gt; Promise.resolve(…
Mid PDF Detailed
Example of mocking fetch in a test: import { render, screen, waitFor } from '@testing-library/react'; import MyComponent from './MyComponent'; test('fetches and displays data', async () => { global.fetch = jest.fn(() => Promise.resolve({ json: () => Promise.resolve({ message: 'Data loaded' }), }) ); render(<MyComponent />);
Short answer: wait waitFor(() =&gt; screen.getByText('Data loaded')); expect(screen.getByText('Data loaded')).toBeInTheDocument(); }); Here, we mock the fetch function to return mock data, then test whether it appears in…
Mid PDF Detailed
React Developer Tools:?
Short answer: Use the Profiler tab to measure the render times and identify slow components. Check for unnecessary re-renders and optimize with React.memo or shouldComponentUpdate. Real-world example (ShopNest) ShopNest’…
Mid PDF Detailed
Mock axios:?
Short answer: import axios from 'axios'; jest.mock('axios'); axios.get.mockResolvedValue({ data: 'mock data' }); Example code import axios from 'axios'; jest.mock('axios'); axios.get.mockResolvedValue({ data: 'mock data'…
Mid PDF Detailed
Choose a Testing Library: Use libraries like Jest (test runner) and React Testing?
Short answer: Library (for testing React components). Real-world example (ShopNest) ShopNest’s storefront is React: components for ProductCard, CartDrawer, and CheckoutForm, with hooks for local UI state. Say this in the…
Questions on this lesson 0

Sign in to ask a question or upvote helpful answers.

No questions yet — be the first to ask!

React.js Tutorial
Course syllabus

React.js Tutorial

Module 1: React Basics & Setup
Module 2: Props, Events & Lists
Module 3: Forms & Hooks
Module 4: Routing & Data
Module 5: State & Authentication
Module 6: Architecture & React 19
Module 7: Performance
Module 8: Full-Stack & Real-Time
Module 9: Testing & Deployment
Module 10: ShopCart Projects
Toolliyo Assistant
Ask about tutorials, ebooks, training, pricing, mentor services, and support. I use public site content only—not admin or internal tools.

care@toolliyo.com

Need callback? Share your details