MSK Institute LogoMSK.Institute
HomeCourses
Book Free Demo➔Sign In
Free Demo➔
MSK Institute LogoMSK.Institute

Leading computer training academy in Shikohabad for software engineering, Python, web development, and digital literacy.

ISO 9001:2015 Certified Center
Follow & Connect
4.9

Programs & Admissions

  • All CoursesCatalog
  • Learning PathsRoadmaps
  • Student ProjectsShowcase
  • Live Classes & ScheduleLive
  • Upcoming Batches
  • Campuses & LocationsHub
  • Verify Certificates
  • Book Free Demo Class

Resources & Tools

  • Free Online Mock TestsAll Tests
  • NIELIT CCC Mock TestFree
  • Course & Career FinderQuiz
  • Study Material Hub
  • All MSK ToolsHub
  • Keyboard ShortcutsNew
  • TypeQuest Speed LabTyping
  • MSK Code PlaygroundCode
  • Interactive Tutorials
  • Quick Cheatsheets

Institute & Contact

  • About MSK Institute
  • Careers & InternshipsHiring
  • Publications & Blogs
  • Gali No. 3, Near Gyan Jyoti Public School,
    Adarsh Nagar, Shikohabad, Uttar Pradesh 283135
  • +91 83930 42166
  • mskshikohabad@gmail.com
  • Hours:Mon – Sat: 8:00 AM – 7:00 PM | Sun: 10:00 AM – 2:00 PM
  • 4.9 ★(38 Google Reviews)
© 2026 MSK Institute. All rights reserved.•Privacy Policy•Terms of Service•Disclaimer•Contact Us

Shikohabad's Leading Computer & Coding Academy

Home
Courses
Live
Material
Fetching REST APIs with Async Await and State0%
Study Materials
React.js for IntermediateProgress 0%
1.1Component Reusability and Polymorphic Components1.2Render Props Pattern in Modern React1.3Higher-Order Components vs Modern Hooks1.4Compound Components Pattern Explained
7.1Fetching REST APIs with Async Await and State7.2Handling HTTP POST, PUT, and DELETE Mutations7.3Introduction to TanStack Query for Server State7.4Managing Pagination, Caching, and Background Refetch
HomeTutorialsReact.js for IntermediateFetching REST APIs with Async Await and State
Handling HTTP POST, PUT, and DELETE Mutations

Fetching REST APIs with Async Await and State

Beginner12 min read•Updated: 2026-11-18•By Er. Sumit Kumar (MSK Institute)
Study MaterialsCheatsheet

1. REST API Integration Architecture in React

In Single-Page Applications, data does not live inside the HTML bundle. Instead, client-side React communicates asynchronously with backend REST APIs over HTTP using JSON serialization.

A production-grade data fetching workflow must manage:

  1. 1
    The Data Container: Storing the parsed JSON payload.
  2. 2
    The Loading State: Displaying skeletons or spinners while the network request is pending.
  3. 3
    The Error State: Catching network dropouts, non-200 HTTP responses, or JSON parse failures gracefully.
  4. 4
    The Cleanup Guard: Preventing state updates if the component unmounts before the HTTP request resolves.
1[Component Mounts]
2 │
3 ▼
4[Dispatch fetch()] ──> [status = 'loading'] ──> [Render Loading Spinner]
5 │
6 ├─ Success (HTTP 200) ──> [data = payload, status = 'idle'] ──> [Render Data List]
7 └─ Failure (HTTP 500) ──> [error = err, status = 'error'] ──> [Render Error Alert]

2. Implementing Clean Async Data Fetching

In React, useEffect cannot accept an async function directly. The standard pattern defines an async function inside the effect and executes it:

1import React, { useState, useEffect } from 'react';
2 
3export default function CourseDirectory() {
4 const [courses, setCourses] = useState([]);
5 const [loading, setLoading] = useState(true);
6 const [error, setError] = useState(null);
7 
8 useEffect(() => {
9 let isMounted = true; // Cleanup flag against race conditions
10 
11 async function loadCourses() {
12 setLoading(true);
13 setError(null);
14 
15 try {
16 const response = await fetch('/api/courses');
17 
18 // CRITICAL: fetch() does NOT reject on HTTP 404 or 500!
19 if (!response.ok) {
20 throw new Error(`Server returned HTTP ${response.status}: ${response.statusText}`);
21 }
22 
23 const data = await response.json();
24 
25 if (isMounted) {
26 setCourses(data);
27 }
28 } catch (err) {
29 if (isMounted) {
30 setError(err.message || 'An unexpected error occurred');
31 }
32 } finally {
33 if (isMounted) {
34 setLoading(false);
35 }
36 }
37 }
38 
39 loadCourses();
40 
41 return () => {
42 isMounted = false; // Teardown
43 };
44 }, []); // Run on initial mount
45 
46 if (loading) return <div className="spinner">Loading engineering courses...</div>;
47 if (error) return <div className="error-box">Error loading data: {error}</div>;
48 
49 return (
50 <div className="course-grid">
51 {courses.map(c => (
52 <div key={c.id} className="course-card">
53 <h4>{c.title}</h4>
54 <p>{c.description}</p>
55 </div>
56 ))}
57 </div>
58 );
59}

3. The fetch() response.ok Trap

A critical misunderstanding among JavaScript engineers: The native window.fetch() Promise only rejects on complete network failures (e.g. offline, DNS failure).

If a backend server returns HTTP 404 Not Found or HTTP 500 Internal Server Error, fetch() still resolves successfully!

You must explicitly check if (!response.ok) to verify that the HTTP status code is in the 200–299 range before attempting to parse response.json().


Interactive Quiz• Knowledge Check

Practice Quiz

Question 1
Why doesn't a standard try...catch block around fetch() catch an HTTP 404 or 500 response automatically?
Question 2
Why is the async keyword placed on an internal helper function rather than directly on useEffect (e.g. useEffect(async () => ...) is invalid)?
Question 3
What is the purpose of the let isMounted = true boolean flag in the effect?
Question 4
Which HTTP header informs the client that the server is transmitting JSON data?
Question 5
What is the benefit of placing setLoading(false) inside a finally block?
Next Lesson

Handling HTTP POST, PUT, and DELETE Mutations

Continue learning with hands-on practice, examples, and exercises in the upcoming topic.

Related Lessons

Previous LessonNext Lesson
Combining useReducer with Context APIHandling HTTP POST, PUT, and DELETE Mutations

Practice Quiz

Test your understanding of this lesson with 5 questions. Each question has one correct answer.

Mentor-Led Practical Training

Master React.js for Intermediate with Hands-On Projects

Practice in live mentor-led sessions with real projects, mock tests, and verifiable certification at MSK Institute.

View Full CourseBook Free Demo
PreviousNext
PreviousPrevNext