Fetch API & JSON in React JS
Course: React JS Training
Topic: Fetch API & JSON
Course Link: React JS Training
Demo Link: Register for a Course Demo
1. Introduction: Why Web Pages Need to Talk to Servers
Think about what happens when you open an online shop. The page structure arrives as HTML, but the product list, your cart contents and your account name do not live inside that HTML file. They live in databases on a server, and the page asks for them after it loads, then inserts them into the document. Search results, social feeds, news lists and dashboards all work the same way: the browser requests data from a server, and JavaScript puts the answer on the page.
The browser feature that makes these requests possible is the Fetch API, and the text format servers almost always answer in is JSON. For this course the topic matters twice over. First, it completes your plain JavaScript toolkit: without it you can change a page, but you can never bring new information into it. Second, it is the direct foundation for React — a React application is mostly components plus data fetched from APIs, and the fetch calls you will write inside useEffect later are exactly the ones you practise here.
On this page you will learn what fetch() and JSON are, how a request travels, how to read the response, how to send data, how to handle failure, and which mistakes beginners make most often.
2. What Is the Fetch API?
In simple words: the Fetch API is a tool built into the browser that lets JavaScript talk to a server. You call one function, fetch(), the browser handles the network work in the background, and the reply comes back to you as a Promise you can wait for.
- Built in. No download, no installation, no import — every modern browser ships it, and recent server-side JavaScript runtimes support it too.
- Promise-based. It fits naturally with
.then() chains and async/await, which you learned in the Modern JavaScript module.
- General purpose. It can read data, send data, set headers and handle JSON, plain text, images and files.
- Modern. It replaces the older
XMLHttpRequest object, which needed callbacks and manual state tracking for the same job.
One-line definition: fetch() starts an HTTP request from the browser and returns a Promise that settles with a Response object.
3. What Is JSON?
JSON stands for JavaScript Object Notation. It is a plain-text format for describing data, written so that it looks very much like a JavaScript object. Live JavaScript objects cannot travel over a network — only text can — so both sides agree on a text format, and JSON is the one nearly every modern API uses.
A typical JSON response body looks like this:
{
"userId": 1,
"id": 1,
"title": "delectus aut autem",
"completed": false
}
It is close to a JavaScript object literal, but not identical. The differences matter when you write JSON by hand or read error messages:
| Feature | In JSON | In a JavaScript object literal |
| Keys | Always double-quoted strings | Bare words or any quoted string |
| String values | Double quotes only | Single, double or backtick quotes |
| Trailing comma after the last item | Not allowed | Allowed |
| Comments | Not allowed | Allowed |
Functions and undefined | Cannot appear | Can appear |
The typical round trip in every app: the server sends JSON text, your code converts it into a real JavaScript value, you work with it, and when you send data back you convert your value into JSON text first.
4. Key Terms You Will Meet
These words appear throughout this page and in every API discussion you will ever read:
- HTTP / HTTPS — the protocol, meaning the agreed set of message rules, that browsers and servers use to talk. HTTPS is the same conversation encrypted.
- Request — the message your browser sends, saying something like "GET me this URL" or "POST this new record".
- Response — the server's reply, containing a status, some headers and usually a body with data.
- Endpoint — one address on a server that answers one kind of request, for example one URL for the list of users and another for a single product.
- Status code — a three-digit number summarising the outcome:
200 for success, 404 for "not found", 500 for a server error.
- Headers — small metadata lines travelling with a request or response.
Content-Type, for instance, declares the format of the body.
- Body (payload) — the actual data carried by a request or response, as opposed to its metadata.
- Promise — a placeholder for a value that will arrive later;
fetch() returns one immediately.
- async / await — syntax that lets you wait for a Promise without chaining
.then() calls.
- CORS — a browser security rule: a server must explicitly allow your site's origin to read its responses, otherwise the browser blocks the data and fetch reports a network error.
5. Syntax of a Fetch Call
The function takes up to two arguments and always returns a Promise:
fetch(url);
fetch(url, options);
- url — the address to request, as a string.
- options — an optional object configuring the request: HTTP method, headers, a body and more. With no options, fetch performs a simple GET.
Style one: promise chains
fetch("https://jsonplaceholder.typicode.com/todos/1")
.then(function (response) {
return response.json();
})
.then(function (data) {
console.log(data);
})
.catch(function (error) {
console.log("Request failed:", error);
});
Each .then() waits for the previous step, and .catch() handles any failure along the way.
Style two: async/await, the preferred modern style
async function loadTodo() {
try {
const response = await fetch("https://jsonplaceholder.typicode.com/todos/1");
const data = await response.json();
console.log(data);
} catch (error) {
console.log("Request failed:", error);
}
}
loadTodo();
Both styles do the same job. The async/await version reads top to bottom like ordinary code, which is why most teams prefer it — you will meet both styles in real projects and React codebases.
The most useful options
| Option | What it does | Example value |
method | Chooses the HTTP verb | "POST" |
headers | Sets metadata lines such as the body format | { "Content-Type": "application/json" } |
body | Carries the data you send; must be a string for JSON | JSON.stringify(myData) |
6. How a Fetch Request Works, Step by Step
It helps to picture the journey of one request. Here is what happens, in order:
- Your code calls
fetch(url, options). The browser builds an HTTP request from the URL and options.
- The browser sends the request to the server. An awaited function pauses here; with
.then() style, the rest of your code keeps running until the reply arrives.
- The server processes the request and sends back a response: a status line, headers and a body.
- The fetch Promise settles as soon as the headers arrive, possibly before the whole body has downloaded. What you receive is a Response object — an envelope around the data, not the data itself.
- You read the body with a method such as
response.json(). This returns a second Promise, so it needs its own await.
- Only now do you hold plain JavaScript data, ready to loop over, filter or render into the DOM.
Steps four and five are the classic beginner trap, so here they are side by side:
async function getData() {
// Step one: wait until the response headers arrive
const response = await fetch(url);
// Step two: wait until the body is read and parsed
const data = await response.json();
return data;
}
Two awaits, two different things: response describes the reply, data is the reply's content.
7. Reading the Response Object
The Response object tells you everything about the reply before you commit to reading its body:
async function inspect() {
const response = await fetch("https://jsonplaceholder.typicode.com/todos/1");
console.log(response.status); // 200
console.log(response.ok); // true, because the status is in the 200-299 range
const data = await response.json();
console.log(data);
}
inspect();
Output:
200
true
{ userId: 1, id: 1, title: 'delectus aut autem', completed: false }
status — the numeric status code.
ok — a convenience boolean, true when the status is in the 200–299 success range.
statusText — the short standard phrase for the status, such as "OK".
url — the final URL of the response, useful after redirects.
headers — the response headers, readable with response.headers.get("Content-Type").
Ways to read the body
JSON is the most common body format, but not the only one. The Response offers one reading method per format:
| Method | Returns | Use it when the body is |
response.json() | A parsed JavaScript value | JSON, the usual case for APIs |
response.text() | A plain string | Raw text, HTML fragments, CSV |
response.blob() | A Blob | Images, PDFs, downloaded files |
response.formData() | A FormData object | Multipart form submissions |
response.arrayBuffer() | An ArrayBuffer | Low-level binary data |
Important: a response body can be read only once. Calling response.json() a second time throws an error. Store the parsed result in a variable and reuse that.
Status code families
| Range | Meaning | Common examples |
| 200–299 | Success | 200 OK, 201 Created |
| 300–399 | Redirect, the resource has moved | 301 Moved Permanently |
| 400–499 | The client made a mistake | 400 Bad Request, 401 Unauthorised, 404 Not Found |
| 500–599 | The server made a mistake | 500 Internal Server Error |
8. Worked Example: Loading Data into the Page
Here is a complete, realistic flow that combines this sub-module with the DOM skills from earlier in the module: fetch a list of users and build one list item per user. The examples use JSONPlaceholder, a public practice API made for exactly this kind of exercise.
The HTML only needs an empty list:
<ul id="user-list"></ul>
The JavaScript does the rest:
async function loadUsers() {
const response = await fetch("https://jsonplaceholder.typicode.com/users");
if (!response.ok) {
throw new Error("Request failed with status " + response.status);
}
const users = await response.json();
const list = document.getElementById("user-list");
for (const user of users) {
const item = document.createElement("li");
item.textContent = user.name + " (" + user.email + ")";
list.appendChild(item);
}
}
loadUsers();
In words: the script requests the users endpoint, stops if the server signalled an error, converts the JSON body into an array of objects, then loops over the array and appends one <li> per user using textContent, which keeps the content safe.
Output in the page:
Leanne Graham ([email protected])
Ervin Howell ([email protected])
... and eight more users
9. Sending Data with POST
GET asks the server for data. POST gives the server new data — a new blog post, a signup form, an order. Compared with the GET examples, three things change:
- add
method: "POST" to the options;
- add a
Content-Type header so the server knows the body is JSON;
- convert your object to text with
JSON.stringify() and pass it as body.
async function createPost() {
const newPost = {
title: "My first post",
body: "This post was created with the Fetch API.",
userId: 1
};
const response = await fetch("https://jsonplaceholder.typicode.com/posts", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(newPost)
});
const created = await response.json();
console.log(created);
}
createPost();
Output:
{
title: 'My first post',
body: 'This post was created with the Fetch API.',
userId: 1,
id: 101
}
The practice server stores nothing permanently, but it echoes your object back and adds an id. That mimics what a real backend does after saving a record: it confirms the creation and returns the new resource, including its database id.
10. Updating and Deleting: PUT, PATCH and DELETE
REST APIs use a small set of verbs, each with a distinct job. Together they cover almost everything an application does with data:
| Method | Purpose | Sends a body? |
GET | Read data | No |
POST | Create a new resource | Yes |
PUT | Replace a resource completely | Yes |
PATCH | Change only some fields of a resource | Yes |
DELETE | Remove a resource | Usually no |
The difference between PUT and PATCH confuses many beginners: PUT says "here is the complete new version, throw the old one away", while PATCH says "here are just the fields that changed". Both are shown below:
// PUT: replace the whole todo
fetch("https://jsonplaceholder.typicode.com/todos/1", {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
userId: 1,
id: 1,
title: "Replaced title",
completed: true
})
});
// PATCH: change only one field of the todo
fetch("https://jsonplaceholder.typicode.com/todos/1", {
method: "PATCH",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ completed: true })
});
// DELETE: remove the todo, no body needed
fetch("https://jsonplaceholder.typicode.com/todos/1", {
method: "DELETE"
});
Each call targets the same endpoint as a read request but with a different verb: the URL identifies what, the method says what to do with it.
11. Handling Errors Properly
Here is the single most surprising fact about fetch: the fetch Promise rejects only for network-level failures. If the server cannot be reached, if the domain does not exist or if CORS blocks the request, the Promise rejects. But if the server answers with 404 Not Found or 500 Internal Server Error, the Promise resolves normally — from fetch's point of view the request succeeded, because a reply arrived.
The two kinds of failure
- Network errors — the request never got a usable answer. The Promise rejects and your
catch block runs.
- HTTP errors — the server answered with a 4xx or 5xx status. The Promise still resolves,
response.ok is false, and you must notice and react.
The standard pattern checks response.ok and throws, so that both kinds of failure end up in the same catch:
async function loadUser(id) {
try {
const response = await fetch("https://jsonplaceholder.typicode.com/users/" + id);
if (!response.ok) {
// The server answered, but with an error status
throw new Error("Server responded with status " + response.status);
}
const user = await response.json();
console.log(user);
} catch (error) {
// Network problems AND the error thrown above both land here
console.log("Something went wrong:", error.message);
}
}
loadUser(1); // logs the user object
loadUser(9999); // no such user, so this logs the error message
The second call receives a 404, response.ok is false, your own throw fires, and the catch prints a readable message instead of your code silently treating nothing as data.
12. JSON.stringify and JSON.parse in Practice
response.json() is really a convenience wrapper around "read the body as text, then run JSON.parse() on it". You will call the two conversion functions directly whenever JSON appears outside a response — when building request bodies, or when saving data in localStorage, the next sub-module of this course.
const book = { title: "Clean Code", pages: 464 };
// JavaScript value → JSON text
const jsonText = JSON.stringify(book);
console.log(jsonText);
// {"title":"Clean Code","pages":464}
// JSON text → JavaScript value
const backToObject = JSON.parse(jsonText);
console.log(backToObject.title); // Clean Code
Not everything survives the round trip, because JSON is a data format, not a JavaScript dump:
| JavaScript value | After a JSON round trip |
Numbers, strings, booleans, null | Unchanged |
undefined, functions | Dropped from objects; become null inside arrays |
Date objects | Become strings in ISO format |
NaN, Infinity | Become null |
Also remember that JSON.parse() throws a SyntaxError if the text is not valid JSON — one stray single quote or trailing comma is enough — so wrap the parsing of untrusted text in try/catch.
13. Common Mistakes with Fetch and JSON
Almost every beginner stumbles on the same handful of issues. Knowing them in advance saves hours of confusion:
- Expecting fetch to reject on 404 or 500. It does not; check
response.ok yourself, as shown in the error-handling section.
- Forgetting the second await.
response.json() returns a Promise. Skip its await and you log a pending Promise instead of your data.
- Treating the Response as the data. The Response is an envelope; the contents arrive only after
json() or text().
// Wrong: a Response object has no "name" property
const response = await fetch(url);
console.log(response.name); // undefined
// Right: read the body first, then use the data
const response = await fetch(url);
const user = await response.json();
console.log(user.name);
- Reading the body twice.
response.json() consumes the body; a second call throws. Parse once and store the result.
- Sending an object as the body without
JSON.stringify(). A body must be a string; an unstringified object turns into the useless text [object Object].
- Forgetting the
Content-Type header on POST requests. Without it, many servers will not try to read the body as JSON at all.
- Blaming fetch for CORS errors. A
TypeError about a failed fetch while the network is fine usually means the server does not allow your origin — a server-side configuration issue, not a bug in your code.
14. Real-World Pattern: Dynamic URLs and Query Parameters
Real applications rarely request one fixed address. A shop filters products by category, a blog loads posts by author, a dashboard asks for one user's records. APIs accept these variations in two places: path parameters, which are part of the address itself, and query parameters, which come after a ? and refine the request.
https://jsonplaceholder.typicode.com/users/3 <-- path parameter: user number 3
https://jsonplaceholder.typicode.com/posts?userId=1 <-- query parameter: posts of user 1
Building URLs with template literals
Path parameters are simplest with a template literal, because the variable sits right inside the string:
async function loadUser(id) {
const response = await fetch(`https://jsonplaceholder.typicode.com/users/${id}`);
const user = await response.json();
console.log(user.name);
}
loadUser(3); // Clementine Bauch
Building URLs with URLSearchParams
Query parameters are safer with URLSearchParams, a built-in helper that assembles the query string and escapes special characters for you. Spaces, & symbols and accented letters in user input would otherwise break or corrupt the URL:
const params = new URLSearchParams({
userId: 1,
_limit: 5
});
const url = "https://jsonplaceholder.typicode.com/posts?" + params.toString();
console.log(url);
// https://jsonplaceholder.typicode.com/posts?userId=1&_limit=5
const response = await fetch(url);
For a single value inside the path itself, encodeURIComponent() does the same escaping job on its own:
function buildSearchUrl(term) {
return "https://example-api.com/search/" + encodeURIComponent(term);
}
Rule of thumb: anything a user typed or that came from data goes through an encoder before it enters a URL.
15. Real-World Pattern: Loading, Error and Data States
Every interface that fetches data passes through the same three moments, and professional code plans for all three:
| State | What the user sees | What the code does |
| Loading | A "Loading..." message or spinner | The request is in flight |
| Data | The actual content | The request succeeded and was parsed |
| Error | A friendly failure message | The network or the server failed |
A blank screen after a failed request is the mark of beginner code. Here is the pattern written with plain DOM tools:
const listEl = document.getElementById("list");
const statusEl = document.getElementById("status");
async function loadPosts() {
statusEl.textContent = "Loading posts...";
try {
const response = await fetch("https://jsonplaceholder.typicode.com/posts?_limit=5");
if (!response.ok) {
throw new Error("Server responded with status " + response.status);
}
const posts = await response.json();
statusEl.textContent = "";
for (const post of posts) {
const item = document.createElement("li");
item.textContent = post.title;
listEl.appendChild(item);
}
} catch (error) {
statusEl.textContent = "Could not load posts. Please try again.";
console.log(error.message);
}
}
loadPosts();
The user now always sees something meaningful: the loading message while waiting, the list on success, or the error message on failure. Keep this trio in mind — in the React part of the course these three states become three pieces of state managed with hooks, and the fetching logic itself stays exactly as it is here.
16. Real-World Pattern: Multiple Requests at Once
Pages often need data from more than one endpoint: a profile page wants the user and that user's posts. There are two ways to run several requests, and choosing wrong makes pages visibly slower.
| Approach | How it runs | Best for |
| Sequential awaits (one after another) | Each request starts only when the previous one finished | When the second request needs a value from the first |
Parallel with Promise.all | All requests start together; you wait once for all of them | Independent requests — the common case |
Parallel requests with Promise.all
async function loadUserAndPosts(userId) {
const [userResponse, postsResponse] = await Promise.all([
fetch("https://jsonplaceholder.typicode.com/users/" + userId),
fetch("https://jsonplaceholder.typicode.com/posts?userId=" + userId)
]);
const user = await userResponse.json();
const posts = await postsResponse.json();
return { user: user, posts: posts };
}
loadUserAndPosts(1).then(function (result) {
console.log(result.user.name); // Leanne Graham
console.log(result.posts.length); // 10
});
Both requests leave the browser at the same moment, so the total wait is roughly the time of the slowest one, not the sum of both. Promise.all resolves with an array of results in the same order as the inputs, which the destructuring above unpacks neatly. One caveat: if any request fails, Promise.all rejects immediately, so wrap the whole thing in try/catch when using await.
17. Real-World Pattern: A Reusable Fetch Helper
By now every example repeats the same ritual: fetch, check response.ok, parse JSON. Real projects extract that ritual into one small function, so the rules live in exactly one place:
async function requestJson(url, options = {}) {
const response = await fetch(url, options);
if (!response.ok) {
throw new Error("Request failed with status " + response.status);
}
return response.json();
}
Using it, application code shrinks to the interesting part:
async function showTodos() {
try {
const todos = await requestJson("https://jsonplaceholder.typicode.com/todos?_limit=3");
console.log(todos);
} catch (error) {
console.log("Could not load todos:", error.message);
}
}
showTodos();
Later you can extend the helper in one spot instead of twenty: extra headers, timeouts, logging. In React projects this little function grows into a small API layer — a single module that every component calls for data. Writing it now is excellent preparation.
18. Common Mistakes and Their Fixes
Part one listed the classic beginner slips. Here are five more, each shown the wrong way and the right way.
Mistake: awaiting fetch inside a loop
// Wrong: requests run one by one, total time adds up
for (const id of ids) {
const response = await fetch(base + id);
const item = await response.json();
results.push(item);
}
// Right: start them all at once, then wait for everyone
const responses = await Promise.all(ids.map(id => fetch(base + id)));
const results = await Promise.all(responses.map(r => r.json()));
Mistake: forgetting that an async function returns a Promise
// Wrong: data is a Promise, not the users
const data = loadUsers();
console.log(data[0].name); // undefined, then an error
// Right: wait for the function to finish
async function main() {
const data = await loadUsers();
console.log(data[0].name);
}
main();
Mistake: parsing before checking the status
// Wrong: on a 500 the body is often an HTML error page,
// so .json() throws a confusing SyntaxError first
const response = await fetch(url);
const data = await response.json();
if (!response.ok) { /* too late */ }
// Right: decide based on the status, then parse
const response = await fetch(url);
if (!response.ok) {
throw new Error("Status " + response.status);
}
const data = await response.json();
Mistake: assuming the body is always valid JSON
Proxy pages, error pages and misconfigured servers sometimes return HTML. Parse defensively when the source is not under your control:
const text = await response.text();
try {
const data = JSON.parse(text);
console.log(data);
} catch (error) {
console.log("Response was not JSON. First 100 characters:", text.slice(0, 100));
}
Mistake: pasting raw user input into a URL
// Wrong: a space or & in the search term breaks the request
const response = await fetch("/search?q=" + searchBox.value);
// Right: let URLSearchParams encode it
const params = new URLSearchParams({ q: searchBox.value });
const response = await fetch("/search?" + params.toString());
19. Best Practices for Fetch and JSON
| Practice | Why it matters |
Check response.ok before parsing | Fetch resolves on 404 and 500 too; only you can decide that an error status is a failure |
Use async/await with one try/catch per flow | Reads top to bottom and funnels every failure — network or HTTP — into one handler |
| Parse the body once and store the result | A response body can be read only once |
Set Content-Type: application/json and JSON.stringify() on every POST, PUT and PATCH | Without them most servers cannot understand the body |
| Escape all dynamic URL parts | URLSearchParams and encodeURIComponent() prevent broken and dangerous requests |
| Show loading and error states | The user should never face a silent blank screen |
Prefer Promise.all for independent requests | Parallel requests cut waiting time dramatically |
| Keep fetching code and DOM code in separate functions | Separation of concerns — and it maps directly onto React components later |
Security note: anything in front-end code can be read by anyone using the page. API keys, tokens and passwords never belong in browser JavaScript; they belong on a server that the browser talks to. Practice APIs like the ones used here exist precisely so you can learn without needing secret keys.
20. Practical Project: Task Manager That Reads and Writes Data
This small project ties the whole module together: it selects elements, listens to events, fetches a list with GET, displays it, and adds new items with POST — including loading and error states. Save the two files in one folder and open the HTML file in your browser.
Step one: build the HTML skeleton
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Task Manager</title>
</head>
<body>
<h1>My Tasks</h1>
<p id="status"></p>
<form id="task-form">
<input id="task-title" type="text" placeholder="New task title" required>
<button type="submit">Add task</button>
</form>
<ul id="task-list"></ul>
<script src="script.js"></script>
</body>
</html>
Step two: write the script
const statusEl = document.getElementById("status");
const form = document.getElementById("task-form");
const input = document.getElementById("task-title");
const list = document.getElementById("task-list");
const API = "https://jsonplaceholder.typicode.com/todos";
function setStatus(message) {
statusEl.textContent = message;
}
function renderTasks(tasks) {
list.textContent = "";
for (const task of tasks) {
const item = document.createElement("li");
item.textContent = task.completed ? "[done] " + task.title : task.title;
list.appendChild(item);
}
}
async function loadTasks() {
setStatus("Loading tasks...");
try {
const response = await fetch(API + "?_limit=5");
if (!response.ok) {
throw new Error("Server responded with status " + response.status);
}
const tasks = await response.json();
setStatus("");
renderTasks(tasks);
} catch (error) {
setStatus("Could not load tasks. Please refresh the page.");
console.log(error.message);
}
}
async function addTask(event) {
event.preventDefault();
const newTask = { title: input.value, completed: false, userId: 1 };
try {
const response = await fetch(API, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(newTask)
});
if (!response.ok) {
throw new Error("Server responded with status " + response.status);
}
const saved = await response.json();
const item = document.createElement("li");
item.textContent = saved.title;
list.appendChild(item);
input.value = "";
setStatus("Task added.");
} catch (error) {
setStatus("Could not add the task. Please try again.");
console.log(error.message);
}
}
form.addEventListener("submit", addTask);
loadTasks();
Step three: run it and understand the flow
- Open the page. The script calls
loadTasks(), which shows "Loading tasks...", requests five todos, checks response.ok, parses the JSON and renders one list item per task.
- Type a title such as Revise fetch states and submit.
addTask prevents the default page reload, stringifies the new task, POSTs it with the JSON content type, reads the echoed response, and appends the saved item to the list.
- The status line reports "Task added.", then the input clears for the next entry.
- Break it on purpose: temporarily change the URL to a wrong path, refresh, and confirm the friendly error message appears instead of a silent blank list.
Expected behaviour: five tasks appear on load, submitted tasks join the list instantly, and every failure produces a visible message. JSONPlaceholder pretends to save your POST — in a real backend the task would also survive a refresh, which is exactly the difference a database makes.
21. Practice Exercises
- Fetch
https://jsonplaceholder.typicode.com/users and render each user's name and company name as rows of a table you build with DOM methods.
- Request only the posts of user 2 using
URLSearchParams, and print how many posts came back.
- Fetch a user and that user's albums in parallel with
Promise.all, then log both results from the destructured array.
- Write the
requestJson helper and rewrite two earlier examples from this page to use it.
- Build a search box over
/users: fetch all users once, then filter the parsed array by name as the user types — no new request per keystroke.
- Request
/posts/9999 on purpose, catch the 404 through your response.ok check, and show a friendly message in the page instead of an unhandled error.
- Fetch five todos, store the array in a variable, run
JSON.stringify() on it and log the resulting text — the exact move you will later use to save data in localStorage.
22. Interview Questions and Answers
What is the Fetch API and how does it differ from XMLHttpRequest?
The Fetch API is the browser's built-in way to make HTTP requests from JavaScript. It returns a Promise and pairs naturally with async/await, while the older XMLHttpRequest relied on callbacks and manual state tracking. Fetch also handles response streaming and integrates cleanly with modern features such as service workers.
What does fetch() return, and why can't you use the result directly as data?
fetch() returns a Promise that resolves to a Response object — an envelope with status, headers and access to the body. It resolves as soon as the headers arrive, so the body must be read separately with response.json() or response.text(), each of which is itself asynchronous. That is why a correct read takes two awaits.
Why does fetch not throw an error on a 404, and how do you handle HTTP errors?
Fetch rejects only for network-level failures — no connection, DNS failure, blocked request. A 404 or 500 means the server answered, so the Promise resolves normally. The standard pattern is to check response.ok (true for statuses 200–299) and throw an Error yourself, so both failure kinds land in the same catch.
What is JSON and why is it the standard format for APIs?
JSON (JavaScript Object Notation) is a plain-text format for representing data as objects, arrays, strings, numbers, booleans and null. It is lightweight, human-readable, language-independent and maps almost directly onto JavaScript structures, so parsing is built into the language. Servers declare it with the Content-Type: application/json header.
What is the difference between JSON.stringify() and JSON.parse()?
JSON.stringify() serialises a JavaScript value into a JSON string — used when sending data in a request body or storing it. JSON.parse() deserialises a JSON string back into a JavaScript value — used when reading JSON that arrived as text. Not everything survives a round trip: functions and undefined are dropped, and Date objects become strings.
Is response.json() synchronous?
No. It returns a Promise because the body may still be downloading when the Response object arrives. You must await response.json() or chain a .then(). A frequent symptom of forgetting this is logging a pending Promise instead of the data.
How do you send a POST request with a JSON body?
Pass a second argument to fetch() with method: "POST", a headers object containing "Content-Type": "application/json", and a body that is your data run through JSON.stringify(). A successful creation usually returns a 201 status and the saved resource, including its new id.
How would you fetch data for several IDs efficiently?
If the requests are independent, build an array of fetch calls with map and wait once with Promise.all, so they run in parallel and the total wait is roughly the slowest request. Awaiting fetch inside a for loop runs them one after another and multiplies the waiting time. Note that Promise.all rejects as soon as any single request fails.
How does error handling work with async/await?
A rejected Promise behaves like a thrown exception, so try/catch around your await lines catches network failures, your own thrown HTTP errors and JSON parse errors alike. Without a try/catch, the rejection propagates and you get an unhandled promise rejection.
What is CORS, in simple words?
Cross-Origin Resource Sharing is a browser security rule: a server must explicitly state, via response headers, that your site's origin may read its data. If it does not, the browser blocks the response and fetch rejects with a TypeError. The fix belongs on the server, not in your front-end code.
How can you cancel a fetch request?
With an AbortController: create the controller, pass controller.signal in the fetch options, and call controller.abort() to reject the request with an abort error. Typical uses are search-as-you-type, where older slower requests should not overwrite newer results, and cleaning up when a component disappears.
Where does fetch fit into React development?
In a React application the fetching logic you learned here stays the same, but the result goes into component state instead of direct DOM manipulation: you call fetch inside useEffect (or in a handler), store the parsed data with a state setter, and React renders from that state. The loading/error/data states you practised here become three state variables — which is why this topic is assumed knowledge before the React module.
23. Quick Revision Checklist
fetch(url, options) returns a Promise that resolves to a Response object — an envelope, not the data.
- Reading the body is a second, separate await:
response.json(), response.text(), response.blob().
- A response body can be consumed only once.
response.ok is true only for 200–299; fetch does not reject on 404 or 500.
- Handle both failure kinds: network errors reject, HTTP errors need your own
ok check and throw.
- POST/PUT/PATCH need
method, Content-Type: application/json and a JSON.stringify()-ed body.
- PUT replaces a whole resource; PATCH changes selected fields; DELETE usually sends no body.
JSON.stringify(): value to text. JSON.parse(): text to value, and it throws on invalid JSON.
- Escape dynamic URL parts with
URLSearchParams or encodeURIComponent().
- Use
Promise.all for independent parallel requests; sequential awaits only when one request depends on another.
- Every fetching UI needs three states: loading, data, error.
- Never put API keys or secrets in front-end code.
24. Official Documentation and Further Reading
The course materials for this topic do not list official specification pages, so treat the references below as curated further reading. They show where the skills on this page travel next: fetching is the data skill behind every React application, and the shift toward server-first rendering described in current React writing builds directly on the request/response model you have just learned.
Conclusion
With this page, the browser side of your foundation is complete. You can now build a page, style it, script its behaviour — and feed it live data: request it with fetch(), inspect the Response, parse the JSON, send data back with POST, PUT, PATCH and DELETE, and fail gracefully when the network or the server lets you down. The loading/error/data pattern and the reusable helper you wrote here are not throwaway exercises; they are the same shapes you will meet in React components, where fetched data flows into state instead of the DOM.
One bridge remains in this module: the browser can also remember data on the visitor's own machine, and the tools for that are JSON.stringify() and JSON.parse() — the exact conversion pair you mastered here — applied inside localStorage. That is the next sub-module, and after it you carry a complete, data-capable JavaScript toolkit into the React part of the course.
Learn more in the React JS Training course, or register for a course demo.