How do I connect React to a REST API with proper loading and error states?

posée a month ago117 vuesen

3

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.

posée a month ago

3 réponses

5
Réponse acceptée

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é.

answered a month ago
4

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é.

answered a month ago
3

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é.

answered a month ago

Sign in and verify your email to post an answer.