Week 10: Fetch API & localStorage
JS | async/await, JSON, Fetch API, localStorage
- Fetch API و localStorage — شرح عملي — ملف workshops.json وتحميله بـ fetch و async / await مع حالتي التحميل والخطأ، المفضلة وآخر تصفية والوضع الداكن في localStorage، ومسودة الاستمارة في sessionStorage · 10 دقائق
Week 10 - Fetch API & localStorage
Web Development 1 — Al-Aqsa University
JSON (JavaScript Object Notation)
JSON is a lightweight text format for storing and exchanging data. It looks very similar to JavaScript objects but with stricter rules. Almost all APIs return data in JSON format.
JSON Rules
- Keys must be strings in double quotes
- Values can be: strings, numbers, booleans, null, arrays, objects
- No trailing commas
- No functions, undefined, or comments
// Valid JSON:
{
"name": "Ahmad",
"age": 25,
"isStudent": true,
"courses": ["Web Dev", "Database"],
"address": {
"city": "Gaza",
"country": "Palestine"
},
"graduationDate": null
}
JSON.stringify() - Object to JSON String
const student = {
name: "Ahmad",
age: 25,
courses: ["Web Dev", "Database"]
};
// Convert to JSON string
const jsonString = JSON.stringify(student);
console.log(jsonString);
// '{"name":"Ahmad","age":25,"courses":["Web Dev","Database"]}'
console.log(typeof jsonString); // "string"
// Pretty-printed JSON (with 2-space indentation)
const pretty = JSON.stringify(student, null, 2);
console.log(pretty);
// {
// "name": "Ahmad",
// "age": 25,
// "courses": [
// "Web Dev",
// "Database"
// ]
// }
JSON.parse() - JSON String to Object
const jsonStr = '{"name":"Ahmad","age":25}';
// Convert JSON string to JavaScript object
const obj = JSON.parse(jsonStr);
console.log(obj.name); // "Ahmad"
console.log(obj.age); // 25
console.log(typeof obj); // "object"
// Be careful with invalid JSON
try {
JSON.parse("not valid json");
} catch (error) {
console.error("Invalid JSON!", error.message);
}
localStorage
localStorage allows you to store data in the browser that persists even after the browser is closed. Data is stored as key-value pairs where both keys and values must be strings.
// ---- Basic Operations ----
// Save data
localStorage.setItem("username", "Ahmad");
localStorage.setItem("theme", "dark");
// Read data
const username = localStorage.getItem("username");
console.log(username); // "Ahmad"
// Non-existent key returns null
console.log(localStorage.getItem("xyz")); // null
// Remove specific item
localStorage.removeItem("theme");
// Clear ALL localStorage data
localStorage.clear();
// ---- Storing Objects and Arrays ----
// Must use JSON.stringify() to save, JSON.parse() to read
const user = {
name: "Ahmad",
age: 25,
courses: ["Web Dev", "Database"]
};
// Save object
localStorage.setItem("user", JSON.stringify(user));
// Load object
const savedUser = JSON.parse(localStorage.getItem("user"));
console.log(savedUser.name); // "Ahmad"
// ---- Save and Load Array ----
const todos = [
{ text: "Learn JavaScript", done: true },
{ text: "Build a project", done: false }
];
// Save
localStorage.setItem("todos", JSON.stringify(todos));
// Load (with fallback for first time)
const savedTodos = JSON.parse(localStorage.getItem("todos")) || [];
console.log(savedTodos);
// ---- Practical Pattern ----
// Load data or use default
function loadData(key, defaultValue) {
const data = localStorage.getItem(key);
return data ? JSON.parse(data) : defaultValue;
}
// Save data
function saveData(key, value) {
localStorage.setItem(key, JSON.stringify(value));
}
// Usage
let tasks = loadData("tasks", []);
tasks.push({ text: "New task" });
saveData("tasks", tasks);
localStorage Limitations
- ~5-10 MB storage limit per domain
- Only stores strings (must stringify objects)
- Synchronous (can block the main thread for large data)
- No expiration (stays forever until cleared)
- Never store sensitive data (passwords, tokens) in localStorage
sessionStorage
sessionStorage works exactly like localStorage but data is cleared when the browser tab is closed.
// Same API as localStorage
sessionStorage.setItem("tempData", "hello");
const data = sessionStorage.getItem("tempData");
sessionStorage.removeItem("tempData");
sessionStorage.clear();
| Feature | localStorage | sessionStorage |
| Persists after close | Yes | No (cleared) |
| Shared between tabs | Yes (same domain) | No (per tab) |
| Size limit | ~5-10 MB | ~5-10 MB |
| Use case | User preferences, saved data | Temporary form data |
Asynchronous JavaScript
JavaScript is single-threaded — it can only do one thing at a time. But what about operations that take time, like fetching data from a server? We don't want the entire page to freeze while waiting!
This is where asynchronous programming comes in. It allows JavaScript to start a long-running task and continue executing other code while waiting for the task to complete.
Callback Functions
// A callback is a function passed as an argument to another function
// It gets "called back" when the operation is done
// Example: setTimeout (runs after a delay)
console.log("1. Start");
setTimeout(() => {
console.log("2. This runs after 2 seconds");
}, 2000);
console.log("3. End");
// Output order: 1, 3, 2
// "3. End" prints BEFORE "2. This runs..." because setTimeout is async!
// Callback Hell (the problem with callbacks)
getUser(1, (user) => {
getPosts(user.id, (posts) => {
getComments(posts[0].id, (comments) => {
console.log(comments);
// Deeply nested = hard to read!
});
});
});
Promises
A Promise represents the eventual result of an async operation. It can be in one of three states:
- Pending — operation hasn't completed yet
- Fulfilled (resolved) — operation completed successfully
- Rejected — operation failed
// Creating a Promise
const myPromise = new Promise((resolve, reject) => {
const success = true;
setTimeout(() => {
if (success) {
resolve("Data loaded!"); // Fulfilled
} else {
reject("Failed to load"); // Rejected
}
}, 1000);
});
// Consuming a Promise with .then(), .catch(), .finally()
myPromise
.then(result => {
console.log("Success:", result);
})
.catch(error => {
console.error("Error:", error);
})
.finally(() => {
console.log("Done (runs regardless)");
});
// Chaining Promises (solves callback hell!)
getUser(1)
.then(user => getPosts(user.id))
.then(posts => getComments(posts[0].id))
.then(comments => console.log(comments))
.catch(err => console.error(err));
// Promise.all - wait for ALL promises to resolve
const p1 = fetch("/api/users");
const p2 = fetch("/api/posts");
const p3 = fetch("/api/comments");
Promise.all([p1, p2, p3])
.then(responses => {
console.log("All loaded!", responses);
})
.catch(err => {
console.error("One failed:", err);
});
// Promise.race - first one to resolve/reject wins
Promise.race([p1, p2])
.then(first => console.log("First to finish:", first));
async / await
async/await is syntactic sugar over Promises that makes async code look and behave like synchronous code. It's the modern and preferred way to work with Promises.
// Regular Promise chain
fetch("https://jsonplaceholder.typicode.com/users/1")
.then(response => response.json())
.then(user => console.log(user.name))
.catch(err => console.error(err));
// Same thing with async/await (much cleaner!)
async function getUser() {
try {
const response = await fetch("https://jsonplaceholder.typicode.com/users/1");
const user = await response.json();
console.log(user.name);
} catch (error) {
console.error("Error:", error);
}
}
getUser();
// Arrow function version
const getUser = async () => {
try {
const response = await fetch("https://jsonplaceholder.typicode.com/users/1");
const user = await response.json();
return user;
} catch (error) {
console.error(error);
}
};
// Multiple await calls (sequential)
async function loadData() {
const usersRes = await fetch("/api/users"); // Wait
const postsRes = await fetch("/api/posts"); // Then wait
const users = await usersRes.json();
const posts = await postsRes.json();
return { users, posts };
}
// Parallel await (faster!)
async function loadDataParallel() {
const [usersRes, postsRes] = await Promise.all([
fetch("/api/users"),
fetch("/api/posts")
]);
const users = await usersRes.json();
const posts = await postsRes.json();
return { users, posts };
}
Key Rules
await can only be used inside an async function
async functions always return a Promise
- Use
try/catch for error handling (instead of .catch())
Fetch API Introduction
The fetch() function is the modern way to make HTTP requests in JavaScript. It returns a Promise that resolves to a Response object.
// Basic fetch
const response = await fetch("https://jsonplaceholder.typicode.com/posts");
// Response object properties
console.log(response.status); // 200
console.log(response.ok); // true (status 200-299)
console.log(response.statusText); // "OK"
console.log(response.headers); // Headers object
console.log(response.url); // The URL that was fetched
// Extracting data from Response
const data = await response.json(); // Parse as JSON (most common)
const text = await response.text(); // Parse as plain text
const blob = await response.blob(); // Binary data (images, files)
GET Requests
// Simple GET request
async function getPosts() {
try {
const response = await fetch("https://jsonplaceholder.typicode.com/posts");
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
const posts = await response.json();
console.log(posts); // Array of 100 posts
console.log(posts[0].title); // First post title
} catch (error) {
console.error("Failed to fetch:", error);
}
}
getPosts();
// Get single item by ID
async function getPost(id) {
const response = await fetch(`https://jsonplaceholder.typicode.com/posts/${id}`);
const post = await response.json();
return post;
}
// With query parameters
async function searchPosts(userId) {
const url = `https://jsonplaceholder.typicode.com/posts?userId=${userId}`;
const response = await fetch(url);
const posts = await response.json();
return posts;
}
// Display fetched data in the DOM
async function displayUsers() {
const response = await fetch("https://jsonplaceholder.typicode.com/users");
const users = await response.json();
const container = document.querySelector("#users");
container.innerHTML = users.map(user => `
<div class="user-card">
<h3>${user.name}</h3>
<p>${user.email}</p>
<p>${user.phone}</p>
</div>
`).join("");
}
POST Requests
// POST request - sending data to a server
async function createPost(title, body) {
try {
const response = await fetch("https://jsonplaceholder.typicode.com/posts", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
title: title,
body: body,
userId: 1
})
});
if (!response.ok) {
throw new Error("Failed to create post");
}
const newPost = await response.json();
console.log("Created:", newPost);
return newPost;
} catch (error) {
console.error("Error:", error);
}
}
createPost("My New Post", "This is the content.");
// PUT request (update entire resource)
async function updatePost(id, data) {
const response = await fetch(`https://jsonplaceholder.typicode.com/posts/${id}`, {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(data)
});
return response.json();
}
// DELETE request
async function deletePost(id) {
const response = await fetch(`https://jsonplaceholder.typicode.com/posts/${id}`, {
method: "DELETE"
});
return response.ok;
}
Error Handling
// Comprehensive error handling pattern
async function fetchData(url) {
try {
const response = await fetch(url);
// fetch only rejects on NETWORK errors
// HTTP errors (404, 500) still resolve! Check response.ok
if (!response.ok) {
switch (response.status) {
case 400: throw new Error("Bad request");
case 401: throw new Error("Unauthorized");
case 403: throw new Error("Forbidden");
case 404: throw new Error("Not found");
case 500: throw new Error("Server error");
default: throw new Error(`HTTP ${response.status}`);
}
}
const data = await response.json();
return data;
} catch (error) {
// Network errors (offline, DNS fail, CORS) + our thrown errors
if (error.name === "TypeError") {
console.error("Network error - check your connection");
} else {
console.error("Error:", error.message);
}
return null;
}
}
// Usage with loading state
async function loadUsers() {
const container = document.querySelector("#users");
const errorMsg = document.querySelector("#error");
// Show loading
container.innerHTML = "<p>Loading...</p>";
errorMsg.textContent = "";
try {
const response = await fetch("https://jsonplaceholder.typicode.com/users");
if (!response.ok) throw new Error("Failed to load users");
const users = await response.json();
// Display data
container.innerHTML = users.map(u => `<p>${u.name}</p>`).join("");
} catch (error) {
container.innerHTML = "";
errorMsg.textContent = error.message;
}
}
Important: fetch() Does NOT Reject on HTTP Errors!
fetch() only rejects on network failures (offline, DNS error). An HTTP 404 or 500 response still resolves! Always check response.ok or response.status.
Working with Real APIs
REST API Concepts
| HTTP Method | Action | Example |
GET | Read data | Get all users, get one user |
POST | Create data | Create a new user |
PUT | Update (replace) | Update entire user profile |
PATCH | Update (partial) | Update just the email |
DELETE | Delete data | Delete a user |
Free Practice APIs
- JSONPlaceholder:
https://jsonplaceholder.typicode.com (posts, users, comments)
- OpenWeatherMap:
https://api.openweathermap.org (requires free API key)
- PokéAPI:
https://pokeapi.co/api/v2 (Pokemon data, no key needed)
- REST Countries:
https://restcountries.com/v3.1 (country info, no key)
Complete Example: Weather API
// Example using OpenWeatherMap API
const API_KEY = "YOUR_API_KEY"; // Get free key from openweathermap.org
async function getWeather(city) {
const url = `https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${API_KEY}&units=metric`;
try {
const response = await fetch(url);
if (response.status === 404) {
throw new Error("City not found");
}
if (!response.ok) {
throw new Error("Weather data unavailable");
}
const data = await response.json();
// Extract useful data
const weather = {
city: data.name,
temp: Math.round(data.main.temp),
feels_like: Math.round(data.main.feels_like),
humidity: data.main.humidity,
description: data.weather[0].description,
icon: data.weather[0].icon,
wind: data.wind.speed
};
console.log(weather);
return weather;
} catch (error) {
console.error(error.message);
return null;
}
}
// Saving search history to localStorage
function saveSearch(city) {
let history = JSON.parse(localStorage.getItem("searchHistory")) || [];
// Add to front, avoid duplicates
history = history.filter(h => h.toLowerCase() !== city.toLowerCase());
history.unshift(city);
// Keep only last 10
history = history.slice(0, 10);
localStorage.setItem("searchHistory", JSON.stringify(history));
}
Summary
You now know how to work with data persistence (localStorage), asynchronous JavaScript (Promises, async/await), and the Fetch API to communicate with external servers. Practice with the Weather App and Budget Tracker tasks!
Al-Aqsa University — Web Development 1