JavaScript Advanced: Closures, Async and Modules
Fetching Data and Saving It in the Browser
In this lesson you will
- Request data with fetch and async/await
- Check response status and handle errors
- Store and read data with localStorage and JSON
Introduction
Most real websites show data that does not live in the page: weather, products, your messages. The page asks a server for it. The tool for this is fetch. Afterwards you often want to remember things, such as a user's settings, and the browser has storage for that.
The code samples that call a real server are shown as plain code, not run on this page, because they need a network request. The data-handling parts you can run.
The simple explanation
fetch sends a request and returns a promise for the response.
async function loadTodo() {
const response = await fetch("https://jsonplaceholder.typicode.com/todos/1");
const todo = await response.json();
console.log(todo.title);
}
loadTodo();Two awaits: first for the response to arrive, then for its body to be read as JSON.
Quick quiz
What does fetch return?
Always check for errors
fetch only rejects when the network itself fails. A server reply like 404 Not Found is still a successful fetch! Check response.ok.
async function loadUser(id) {
try {
const response = await fetch(`https://example.com/api/users/${id}`);
if (!response.ok) {
throw new Error("Server replied with " + response.status);
}
return await response.json();
} catch (error) {
console.log("Could not load the user:", error.message);
return null;
}
}Sending data
Add options to choose a method and send a body.
await fetch("https://example.com/api/notes", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ text: "Remember the milk" }),
});CORS in one paragraph
Browsers only let a page read a response from another website if that site agrees, using headers (CORS). If you see a CORS error in the console, it is not a bug in your fetch: the server must allow your origin. Never put secret keys in front-end code: anyone can read them.
Working with JSON data
JSON is plain text, so you can practise the handling part without a network. Run this.
Remembering things with localStorage
localStorage saves text in the browser, and it stays after the tab closes. It stores strings only, so use JSON for objects.
const settings = { theme: "dark", fontSize: 18 };
localStorage.setItem("settings", JSON.stringify(settings));
const saved = JSON.parse(localStorage.getItem("settings"));
console.log(saved.theme);
localStorage.removeItem("settings");Useful facts:
sessionStorageworks the same way, but is cleared when the tab closes.- Storage is limited (usually about 5 MB) and not secure. Do not store passwords or private data in it.
- It is separate for each website.
Quick quiz
Which should you NOT store in localStorage?
Try it yourself
Write functions save(key, value) and load(key) that wrap JSON.stringify and JSON.parse. Here you can test them with a plain object that pretends to be storage.
Summary
fetchreturns a promise. Read the body withawait response.json()and checkresponse.ok.- Browsers enforce CORS. Keep secrets out of front-end code.
localStoragekeeps strings between visits. UseJSON.stringifyandJSON.parse.- Never store sensitive data in browser storage.
Lesson complete
+20 XP
Nice work. Keep going while it is fresh.
Sources and further reading