Error handling
API calls can fail because of network issues, bad status codes, or bad data. Use try/catch, check res.ok, and show the user a friendly message instead of a blank screen.
async function getPosts() {
try {
const res = await fetch("/api/posts")
if (!res.ok) throw new Error(`HTTP ${res.status}`)
return await res.json()
} catch (err) {
console.error("Failed to load posts:", err)
return [] // safe fallback
}
}
// In React
{error && <p className="text-red-600">Couldn't load posts. Try again.</p>}