Kijan mwen ka konekte React ak yon API REST?

poze a month ago29 gadeht

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?

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

    davidcharles 5 days ago

1 Repons

1
Repons yo aksepte

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.

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

answered a month ago

Sign in and verify your email to post an answer.