Week 6
Week 6
Last week, our list of interests lived in a JavaScript file that we imported. The page already had the data when it started. A merch site needs to ask for current product information from another service.
This week, we'll click a button to load a list through an HTTP request. We'll inspect the response in the browser, show the returned cards, and handle the cases where the list is empty or the request fails.
We'll use a small JSON file served by our own development server. This gives everyone the same example without needing a shop account or an API token. It is practice for using an API; the file is made-up class data, not a live product catalog.
Getting started
The complete practice files are included at the end of this lesson.
Save and commit your Week 5 work. Open a terminal at the top of practice-page and create a branch from that saved work:
git status
git switch -c load-interests
Copy the supplied Week 6 App.jsx and App.css into react-page/src. Copy interests.json into react-page/public. Keep the existing main.jsx, styles.css and last week's InterestCard.jsx. The new App.jsx still uses InterestCard for each card.
This reference includes a finished request function. For the exercise, find async function loadInterests() in your copy of App.jsx. Replace that entire function with this empty one, leaving the rest of App in place:
function loadInterests() {
}
We'll build the function together. The supplied file keeps the familiar InterestCard ready so we can spend this meeting on requests.
Start the server from react-page:
cd react-page
npm run dev
Open the address printed by the terminal. The page should show Load interests and a message asking you to click. The button will do nothing until we write its function.
Requests and responses
The frontend is the part of an application running in the browser: the page, buttons, and React code we have been writing. A server is a program that receives requests and sends responses. Our Vite development server is one example. A shop's remote backend is another; it can look up stored products and update a cart.
HTTP is the set of rules browsers and servers use to exchange these messages. When our page requests a list, it sends a request to an address. The server returns a response containing information about the result and, usually, some data.
An API, short for application programming interface, describes how software can use another piece of software. For a web API, its documentation tells us which HTTP requests we can make and what responses to expect.
These terms help us read that documentation:
| Term | Meaning in our example |
|---|---|
| URL | The address of the requested resource, such as http://localhost:5173/interests.json. Use your server's actual port. |
| Endpoint | An address an API makes available for a particular operation, such as requesting a product list. |
| Method | The requested action. GET asks to read a resource; a shop API may use POST to create a cart or add items. |
| Headers | Named information about the message, such as Content-Type, which describes the body's format. |
| Body | The data carried by the request or response. Our GET request has no body; the response body contains our list. |
| Status code | A number describing the HTTP result, such as 200 for a successful response or 404 for a resource that was not found. |
The API's documentation chooses the method, address, and fields. We cannot change GET to POST and expect the server to guess what we meant.
Reading JSON
Open public/interests.json. The start should look familiar:
[
{
"id": "games",
"title": "Video games",
"description": "I like learning how games are designed."
}
]
JSON, short for JavaScript Object Notation, is a text format for sending data. This example describes an array containing an object. Unlike our .js file, it has no export, variable declaration, or function. Property names and strings use double quotes. JSON does not allow comments or an extra comma after the last item.
Open /interests.json at the same local address as your app. For example, if your page is at http://localhost:5173, open http://localhost:5173/interests.json. The browser should show the data. The public folder name is not part of that URL.
The text arriving over HTTP still needs to be read as JavaScript data before React can use it. That is what response.json() will do.
State for a request
Look near the start of App. The reference declares three state values:
const [interests, setInterests] = useState([]);
const [status, setStatus] = useState("idle");
const [error, setError] = useState("");
interests starts as an empty array. status starts as "idle", meaning we have not requested the list yet. error starts as an empty string and will hold a message if loading fails.
We chose four status words for the page:
| Page status | What someone should see |
|---|---|
idle |
A button and instructions to load the list. |
loading |
A loading message while the request is unfinished. |
success |
Cards, or an explanation that the returned list is empty. |
error |
An error message and a way to try again. |
These strings are our React state. They are different from the numeric HTTP status code sent by the server.

Follow the two possible results from loading. A valid empty array belongs to success: the request worked, but there are no cards to show. An error needs a different message because the page could not obtain a usable list.
Waiting for a response
fetch() starts an HTTP request. It returns a Promise: a value representing work that will finish later. The request may succeed or fail while the browser keeps responding to other actions.
An async function lets us use await inside it. await pauses the rest of that function until the operation settles; it does not freeze the entire browser.
These are the two lines that receive and read our response:
const response = await fetch("/interests.json");
const data = await response.json();
fetch uses GET by default. The first result is a Response object containing the HTTP status, headers, and access to the body. The second line reads the body as JSON and produces the array. These are two separate steps: receiving a response does not mean we have already parsed its data.
We also need to check whether the response was successful. fetch can return a Response for an HTTP error such as 404. response.ok is true for status codes from 200 through 299. An offline request may fail before any Response arrives.
Handling failures
Before adding the complete function, read the new JavaScript used in it:
if (condition) { ... }runs the instructions in its braces only when the condition is true.!means “not.â€!response.okchecks for a response that was not successful.throw new Error("message")creates an error and stops the current path through the code.trysurrounds work that can fail.catch (failure)runs if an error is thrown there and gives that error the namefailure.failure.messagereads the error's message.+joins strings in these messages.return;ends the function immediately without returning a value.
The error handling is part of making the button useful: someone needs to know when the request did not work and be able to try again.
The provided isInterest function checks each object's fields before we display it. Array.isArray(data) checks the outer list, and .every(isInterest) checks that all its items pass the function. || means “or,†so we reject the response if either check fails.
Replace the empty loadInterests function with:
async function loadInterests() {
if (status === "loading") {
return;
}
setStatus("loading");
setError("");
try {
const response = await fetch("/interests.json");
if (!response.ok) {
throw new Error("The request failed with status " + response.status + ".");
}
const data = await response.json();
if (!Array.isArray(data) || !data.every(isInterest)) {
throw new Error("The response does not contain the interest fields we need.");
}
setInterests(data);
setStatus("success");
} catch (failure) {
setError("Could not load interests. " + failure.message);
setStatus("error");
}
}
At the beginning, we stop if a request is already loading. Otherwise, we show loading and clear an earlier error. After receiving a successful response with valid data, we save the list and show success. A request error, unreadable JSON, or a failed field check takes us to catch.
Save and click Load interests. The cards should appear.
How the response becomes a page update
Receiving JSON does not put cards in the DOM by itself. fetch gets a response, and response.json() reads its body into JavaScript data. After the checks pass, setInterests(data) and setStatus("success") ask React to use that data and status in another render.
React calls App again. The JSX now uses the returned interests to describe cards and the success status to choose its message. React commits the needed DOM changes, then the browser can paint them. Earlier, setStatus("loading") requested the loading version of the same page. The request happens while that document stays open; we are not asking the server for a whole new HTML page.
This is the same state-to-page process as Week 5's search. The new value comes from a response instead of a text field. If we only saved the response in a local variable and never called a setter, React would have no request to update this interface.

Read the picture alongside loadInterests. The response supplies data; the state setters ask React to show it. Which step would fail if the server returned an object instead of the array our page expects?
Checking the response's shape
Look at the supplied check near the top of App.jsx:
function isInterest(value) {
return (
value !== null &&
typeof value === "object" &&
typeof value.id === "string" &&
typeof value.title === "string" &&
typeof value.description === "string"
);
}
null represents an explicitly empty value. !== means “is not equal to.†typeof returns a word describing a value's type. This function requires a non-null object with three string fields.
&& requires each check to pass. JavaScript stops checking after the first false result, so it will not try to read .id from null. We check for null separately because JavaScript's typeof null is "object".
This is a small check for our known class file. It helps us report an unexpected response instead of crashing while drawing cards. A real product response will need checks for its own fields; an isInterest function cannot validate a product or a cart.
Showing what is happening
<button type="button" onClick={loadInterests} disabled={status === "loading"}>
Load interests
</button>
As with onChange last week, we pass the function without calling it. disabled receives a Boolean value. When the comparison is true, the browser prevents someone from pressing the button again.
The page uses conditions to choose messages. For example:
{status === "success" && interests.length === 0 && (
<p>No interests were returned.</p>
)}
=== compares values and && requires both conditions to be true. This paragraph appears when loading succeeded and the returned array has zero items. An empty list is a successful response with nothing to display; it is not the same as a failed request.
In the full file, interests.length > 0 checks for more than zero items. role="status" lets a screen reader announce routine changes, and role="alert" announces an error. The error paragraph also tells you how to retry.
Inspecting the request
Open the browser's developer tools with Inspect, then open Network. Keep the page open and click Load interests again. Find the request named interests.json.
Inspect these parts:
- In Headers, find the request URL, method, and status code. The URL should end in
/interests.jsonand the method should beGET. - In Response or Preview, find the returned array and its objects. This is the data our function passed to
setInterests. - Compare a returned title with the corresponding card on the page.
If loading happens too quickly to notice, use the Network panel's throttling control to slow the connection, then click again. Throttling simulates a slower connection. You should see the loading message and disabled button while the request is pending. Turn throttling off afterward.
No request appears until the button is clicked. The event handler starts the request; there is no automatic load on page opening in this exercise.
Try an empty list and a failure
First, save a copy of the working JSON. Then replace its contents with:
[]
Save and click the button. You should get No interests were returned. Restore the data.
Next, change "title" to "heading" in one object. The JSON is still readable, but it no longer matches the fields our page needs. Load it again. Find the error message and fix the property name. Retry without refreshing the page.
For a network failure, choose Offline in the Network panel and click the button. Restore the normal connection setting before trying again. Do not leave the browser offline when you move on.
The failures tell us different things: an empty array is valid data, a renamed property is the wrong data shape, and an offline browser cannot complete the request.
Comparing this with the merch API
Fourthwall can provide the merch catalog through its Storefront API. One documented request asks for the public products in the all collection:
GET https://storefront-api.fourthwall.com/v1/collections/all/products?storefront_token=YOUR_TOKEN¤cy=USD&page=0&size=50
This line is a request to read, not a command to run. YOUR_TOKEN is a placeholder for the shop's Storefront token. The part after ? contains query parameters: named values separated by &. They identify the storefront, requested currency, and page of results.
Fourthwall's product-list response is an object containing results and paging, not a bare array. results holds the products, and paging.hasNextPage says whether another page exists.
This shortened example uses invented values and omits other product fields:
{
"results": [
{
"type": "PRODUCT",
"id": "example-product",
"name": "Blueprint shirt",
"variants": []
}
],
"paging": {
"hasNextPage": false
}
}
After response.json(), the product array is at data.results, and the first product's name is at data.results[0].name. Our interests use title; Fourthwall products use name. Product variants carry more information, including an ID and price, which we'll use next week.
Changing only the URL in our exercise would not be enough. We would need to read the actual response shape, validate the product fields we use, handle additional pages, and pass product values to product cards. For the initial class project, we'll use ordinary products; the API can also return bundles with different fields.
Open Fourthwall's Fetching Products page (linked under Resources) and find results, paging, and variants. Follow the data from the outer object to one product. This is the same object and array reading we practiced last week.
When another address is blocked
Our JSON file comes from the same address as the page, so the browser lets us read it. A different site, like Fourthwall, is a different origin. The browser only lets our page read its response if that server allows it. This rule is called CORS. Fourthwall allows browser calls to its Storefront API, but not every API does.
If a future request is blocked, read the Console and Network details, check the address, then check the API's instructions for browser access. Adding mode: "no-cors" will not fix it. It hides the response body from our code.
When something goes wrong
| What you see | What to check |
|---|---|
| No request in Network | Confirm the button uses onClick={loadInterests} and the function contains fetch. |
| JSON parsing error or an HTML response | Open the exact request URL. Confirm the file is public/interests.json, not src/interests.json or public/public/interests.json. |
| Wrong-field error | Check id, title, and description and confirm that the outer value is an array. |
| The page stays in loading | Check the Console, keep both success and catch status updates, and make sure you restored normal network settings. |
HTTP 401 or 403 on a future API call |
Read the response and check the service's access instructions and configured token. |
HTTP 404 |
Check the endpoint and resource ID. A missing local path may instead return Vite's HTML page, which causes a JSON parsing error. |
HTTP 429 |
Too many requests were made. Follow the API's retry guidance instead of repeatedly clicking. |
HTTP 500 |
The server reported an error. Keep the error message and retry path useful; changing the page's CSS will not fix the server. |
The meanings of other HTTP codes are listed on the MDN status codes page under Resources.
What's next
Before next week, restore valid JSON and turn off any Network throttling or Offline setting. Add one new interest to the JSON, load it, and check that its card shows. Commit with a message such as Load interests and handle failed requests and push the branch. If GitHub asks you to sign in, use the GitHub CLI steps on the Setup page.
Next week, we'll use state to choose a product variant and update a small practice cart.
Resources
Everything needed for today's code and explanations is above. These are extra examples or references to return to after the exercise.
- MDN: Overview of HTTP
- MDN: Working with JSON
- MDN: Using Fetch
- MDN: async functions
- MDN: try...catch
- MDN: Response.ok
- MDN: typeof
- MDN: CORS
- MDN: HTTP status codes
- Fourthwall: Fetching Products
- Fourthwall: Product fields
Complete practice files
Copy these files into the paths shown below. They are the same files used by the lesson. Keep the filenames and imports together. Keep last week's InterestCard.jsx (or copy the version below if you need it).
src/InterestCard.jsx
export default function InterestCard(props) {
return (
<article className="interest-card">
<h3>{props.title}</h3>
<p>{props.description}</p>
</article>
);
}
src/App.jsx
import { useState } from "react";
import InterestCard from "./InterestCard.jsx";
import "./App.css";
function isInterest(value) {
return (
value !== null &&
typeof value === "object" &&
typeof value.id === "string" &&
typeof value.title === "string" &&
typeof value.description === "string"
);
}
function renderInterest(interest) {
return (
<InterestCard
key={interest.id}
title={interest.title}
description={interest.description}
/>
);
}
export default function App() {
const [interests, setInterests] = useState([]);
const [status, setStatus] = useState("idle");
const [error, setError] = useState("");
async function loadInterests() {
if (status === "loading") {
return;
}
setStatus("loading");
setError("");
try {
const response = await fetch("/interests.json");
if (!response.ok) {
throw new Error("The request failed with status " + response.status + ".");
}
const data = await response.json();
if (!Array.isArray(data) || !data.every(isInterest)) {
throw new Error("The response does not contain the interest fields we need.");
}
setInterests(data);
setStatus("success");
} catch (failure) {
setError("Could not load interests. " + failure.message);
setStatus("error");
}
}
return (
<main>
<h1>Load my interests</h1>
<p>
This practice page requests a JSON file from the same server as the page.
</p>
<button type="button" onClick={loadInterests} disabled={status === "loading"}>
Load interests
</button>
<div role="status">
{status === "idle" && <p>Click the button to request the list.</p>}
{status === "loading" && <p>Loading interests…</p>}
{status === "success" && interests.length > 0 && (
<p>Interests loaded: {interests.length}</p>
)}
{status === "success" && interests.length === 0 && (
<p>No interests were returned.</p>
)}
</div>
{status === "error" && (
<p role="alert">{error} Check the Network tab, then click Load interests to try again.</p>
)}
{status === "success" && (
<div className="interest-list">{interests.map(renderInterest)}</div>
)}
</main>
);
}
src/App.css
.interest-card h3 {
font-size: 1.15rem;
margin: 0;
}
button:disabled {
background: #475569;
cursor: wait;
}
[role="alert"] {
color: #991b1b;
border-left: 4px solid #b91c1c;
padding: 12px;
background: #fef2f2;
}
public/interests.json
[
{
"id": "games",
"title": "Video games",
"description": "I like learning how games are designed."
},
{
"id": "photos",
"title": "Photography",
"description": "I like taking pictures around Hoboken."
},
{
"id": "cooking",
"title": "Cooking",
"description": "I like trying a new recipe each week."
}
]