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

asked a month ago117 viewsen

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?

🤖 AI diagnosis

AI-generated. Not an answer — the community below confirms or corrects it. Always verify before relying on it.

asked a month ago

3 Answers

5
Accepted answer

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.

Sign in to tell others whether this worked.

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.

Sign in to tell others whether this worked.

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.

Sign in to tell others whether this worked.

answered a month ago

Sign in and verify your email to post an answer.