alejandro
alejandro

Reputation: 409

Reactjs. Product detail page not working as expected

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

Answers (1)

bryce
bryce

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

Related Questions