Kijan mwen ka konekte React ak yon API REST?

posée a month ago30 vuesht

1

Mwen gen yon app React e mwen vle chaje done ki soti nan yon API REST.

Mwen eseye sa a:

useEffect(() => {
  fetch('/api/items').then(r => r.json()).then(setItems);
}, []);

Men items toujou vid. Ki sa m ap fè mal?

🤖 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
  • Thanks, this helped. Did you also try clearing the cache?

    davidcharles 5 days ago

1 réponse

1
Réponse acceptée

The issue is a stale closure. Move the fetch into a function and include a cleanup flag:

useEffect(() => {
  let alive = true;
  fetch('/api/items')
    .then(r => r.json())
    .then(d => { if (alive) setItems(d); });
  return () => { alive = false; };
}, []);

If items is still empty, check the Network tab — the endpoint may be returning { data: [...] } rather than an array.

Connectez-vous pour dire si ça a marché.

answered a month ago

Sign in and verify your email to post an answer.