How do I connect React to a REST API with proper loading and error states?
poze a month ago113 gadeen
I'm building a Next.js app and need to fetch from a REST API.
What's the recommended pattern for handling loading, error, and empty states without a lot of boilerplate? Server Components vs client fetching?
🤖 Dyagnostik IA
Se IA ki fè l. Se pa yon repons — kominote a anba a konfime oswa korije l. Toujou verifye anvan ou fye l.
3 Repons
Rule of thumb: const by default, let when you must reassign, never var. var is function-scoped and hoisted, which causes subtle bugs. const doesn't make objects immutable — only the binding.
Konekte pou di lòt moun si li te mache.
ON CONFLICT is what you want:
INSERT INTO items (id, name) VALUES (1, 'a')
ON CONFLICT (id) DO UPDATE SET name = EXCLUDED.name;
For multiple unique columns, name the constraint: ON CONFLICT ON CONSTRAINT items_a_b_key.
Konekte pou di lòt moun si li te mache.
In the App Router, prefer a Server Component and fetch on the server:
export default async function Page() {
const items = await fetch('https://api.example.com/items', { next: { revalidate: 60 } })
.then(r => r.json());
return <List items={items} />;
}
You get loading via loading.tsx and errors via error.tsx for free.
Konekte pou di lòt moun si li te mache.
Sign in and verify your email to post an answer.