I am fetching an API and setting response data in the products array. But, the products array state is not updating and returning an empty array.
here is my code,
const [products, setProducts] = useState([]);
useEffect(() => {
const apiCaller = async () => {
const res = await axios.get('http://127.0.0.1:2000/');
const pro = await res.data;
setProducts(pro);
console.log(products);
}
apiCaller();
}, []);
I have tried passing the ‘products ‘ in the dependency array but that results in infinite renders.
2
Answers
You are getting an empty product array as the state gets updated after the useEffect is unmounted.
So instead of printing product inside useEffect try to write outside it.
If you want to map it after the data you receive you can do it like below inside useEffect:
the reason you can not see the value because the firrst log in inside the async funtion is getting the previous state of products is [] and setProduct is also an async and its updates will not be reflected immediately inside the same render cycle you will see the updated product out side the useEffect