Comment connecter React à une API REST proprement ?

poze a month ago65 gadefr

2

Je cherche la meilleure façon de récupérer des données d'une API REST dans un composant React avec TypeScript.

Dois-je utiliser useEffect directement ou une librairie comme React Query ? Quels sont les pièges courants (course conditions, cleanup) ?

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

poze a month ago

2 Repons

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.

Konekte pou di lòt moun si li te mache.

answered a month ago
2

Use a data-fetching library. @tanstack/react-query handles caching, race conditions and cleanup for you:

const { data, isLoading, error } = useQuery({
  queryKey: ['items'],
  queryFn: () => fetch('/api/items').then(r => r.json()),
});

Rolling your own is fine for one screen, but it doesn't scale.

Konekte pou di lòt moun si li te mache.

answered a month ago

Sign in and verify your email to post an answer.