Kijan mwen ka konekte React ak yon API REST?
asked a month ago31 viewsht
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?
🤖 AI diagnosis
AI-generated. Not an answer — the community below confirms or corrects it. Always verify before relying on it.
asked a month ago
Jean Pierre 1.7k
Thanks, this helped. Did you also try clearing the cache?
— davidcharles 5 days ago
1 Answer
1
✓✓ Accepted answer
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.
Sign in to tell others whether this worked.
answered a month ago
Marie Louis 211
Sign in and verify your email to post an answer.