Serialize your data as JSON, persist it in the browser with localStorage, and retrieve remote data with fetch.
Open this lesson in KodokonJSON is the universal exchange format of the web: it's text whose syntax looks like JavaScript objects (keys in double quotes, no functions). Two methods are all you need: JSON.stringify turns a JavaScript value into a string, JSON.parse goes the other way.
const task = { title: "Review the lesson", done: false };
const json = JSON.stringify(task);
console.log(json);
// {"title":"Review the lesson","done":false}
const parsed = JSON.parse(json);
console.log(parsed.done); // falselocalStorage keeps data in the browser, even after the tab is closed. It's perfect for a chosen theme, a draft, or a task list. Since it only stores text, JSON acts as the bridge: serialize before setItem, deserialize after getItem.
const tasks = [
{ title: "Buy bread", done: false },
{ title: "Review the lesson", done: true }
];
localStorage.setItem("tasks", JSON.stringify(tasks));
const raw = localStorage.getItem("tasks");
const saved = raw ? JSON.parse(raw) : [];
console.log(saved.length); // 2The last building block: fetching data from a server. fetch sends an HTTP request and returns a promise. With async/await, the code reads from top to bottom: you wait for the response, check that it's valid, then wait for the JSON decoding, which is also asynchronous.
async function loadUsers() {
const response = await fetch(
"https://jsonplaceholder.typicode.com/users"
);
if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}
const users = await response.json();
console.log(users[0].name);
}
loadUsers();JSON.stringify do?localStorage.getItem return for a key that does not exist?await response.json() rather than simply response.json()?