Basic GET Request
const res = await fetch('/api/posts');
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const data = await res.json();
POST with JSON
const res = await fetch('/api/posts', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ title: 'Hello' }),
});
Error Handling Wrapper
async function api(url, options = {}) {
const res = await fetch(url, options);
if (!res.ok) {
const err = await res.json().catch(() => ({}));
throw new Error(err.message || res.statusText);
}
return res.json();
}
Loading States
Always handle three states: loading, success, error. Show skeleton UI during fetch, disable submit buttons on POST.