I have a React app, which takes 1+n API calls to fetch data into a list which is a state variable (using useState).
The problem I am facing is, the list has duplicate items. Instead of 10 items, it is being populated with 20.
I do empty the list on running it, but I guess setState works asynchronously. How do I fix this?
const [products, setProducts] = useState([]);
useEffect(() => {
fetch('http://localhost:1234/')
.then((response) => response.json())
.then((data) => {
setProducts([]);
for(let i = 0; i < Math.min(10, data['products'].length); i++) {
fetch('http://localhost:1234/lookup/'+data['products'][i])
.then((response) => response.json())
.then((data) => {
setProducts(products => [...products, data]);
});
}
});
}, []);