Reputation: 409
I am trying to write a detail page for a product.
function ProductDetail() {
const product = useGetProducts(`${API}/6`);
console.log(product);
return (
<>
<h1>ProductDetail</h1>
<ProductItem product={product}/>
</>
);
}
const useGetProducts = (API) => {
const [products, setProducts] = useState([])
useEffect(() => {
async function fetchData() {
const response = await axios(API);
setProducts(response.data)
}
fetchData();
}, []);
return products;
}
If i uncomment :
<ProductItem product={product}/>
Then at console.log I can see the product fetched, but if not then I see an empty array
Upvotes: 0
Views: 48
Reputation: 3051
You should be using await
for asynchronous call in your effect:
useEffect(async () => {
async function fetchData() {
const response = await axios(API);
setProducts(response.data)
}
await fetchData();
}, []);
Upvotes: 1