// fetch() lifecycle fetch(url) .then(response => response.json()) // Step 1: response parse .then(data => console.log(data)) // Step 2: data use .catch(error => console.error(error)); // Error handle
// JSONPlaceholder = free fake API for testing
const URL = 'https://jsonplaceholder.typicode.com/users/1';
// Method 1: .then() chain
fetch(URL)
.then(response => {
console.log(response.status); // 200
console.log(response.ok); // true
return response.json(); // parse JSON
})
.then(user => {
console.log(user.name); // "Leanne Graham"
console.log(user.email);
})
.catch(err => console.error('Failed:', err));
// Method 2: async/await (cleaner)
async function getUser(id) {
const response = await fetch(`https://jsonplaceholder.typicode.com/users/${id}`);
const user = await response.json();
return user;
}
getUser(1).then(user => console.log(user.name));
// Fetch list + display as HTML
async function loadPosts() {
const res = await fetch('https://jsonplaceholder.typicode.com/posts?_limit=5');
const posts = await res.json();
const container = document.getElementById('posts');
container.innerHTML = ''; // clear loading state
posts.forEach(post => {
const div = document.createElement('div');
div.className = 'post-card';
div.innerHTML = `
<h3>${post.title}</h3>
<p>${post.body}</p>
<small>Post #${post.id}</small>
`;
container.appendChild(div);
});
}
loadPosts();
// With loading state
async function loadWithState() {
const container = document.getElementById('posts');
container.innerHTML = '<p>Loading...</p>';
try {
const res = await fetch('https://jsonplaceholder.typicode.com/posts?_limit=5');
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const posts = await res.json();
container.innerHTML = posts.map(p => `<div><h3>${p.title}</h3></div>`).join('');
} catch (err) {
container.innerHTML = `<p style="color:red">Error: ${err.message}</p>`;
}
}
// Query params: ?key=value&key2=value2
const baseURL = 'https://jsonplaceholder.typicode.com';
// Manual
fetch(`${baseURL}/posts?userId=1&_limit=3`);
// URLSearchParams (cleaner)
const params = new URLSearchParams({
userId: 1,
_limit: 3,
_page: 1
});
fetch(`${baseURL}/posts?${params}`);
// → /posts?userId=1&_limit=3&_page=1
// URL object
const url = new URL(`${baseURL}/posts`);
url.searchParams.append('userId', 1);
url.searchParams.append('_sort', 'id');
url.searchParams.append('_order', 'desc');
fetch(url);
ဒီ buttons တွေ နှိပ်ကြည့်ပါ — real API call:
← JSON 01 | Next: JSON 03 → Fetch POST →