How do I connect React to a REST API with proper loading and error states?
posée a month ago117 vuesen
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?
🤖 Diagnostic IA
Généré par IA. Ce n'est pas une réponse — la communauté ci-dessous le confirme ou le corrige. Vérifiez toujours avant de vous y fier.
3 réponses
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.
Connectez-vous pour dire si ça a marché.
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.
Connectez-vous pour dire si ça a marché.
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.
Connectez-vous pour dire si ça a marché.
Sign in and verify your email to post an answer.