I'm trying to dynamically render some components mapping an array of objects from an API call. I can't wrap my head around the syntax of this one.
I have to fetch from this url:
https://fakestoreapi.com/products
And for each object in the array I have to render Product.js inside ProductContainer.js.
ProductContainer.js:
import axios from "axios";
import React, { useState, useEffect } from "react";
import "../styles/ProductContainer.scss";
import Product from "./Product";
const ProductContainer = () => {
const [productArray, setProductArray] = useState("");
const [imgUrl, setImgUrl] = useState("");
const [nameUrl, setNameUrl] = useState("");
const [priceUrl, setPriceUrl] = useState("");
useEffect(() => {
axios.get("https://fakestoreapi.com/products").then((res) => {
setProductArray(res.data);
setImgUrl(res.data.image);
setNameUrl(res.data.title);
setPriceUrl(res.data.price);
});
}, []);
return (
<div className="product-container">
{productArray.map((e) => {
<Product imgUrl={imgUrl} nameUrl={nameUrl} priceUrl={priceUrl} />;
})}
</div>
);
};
export default ProductContainer;
Thank you!
The image, title and price are properties of each product, not of the whole response from the API.
Also productArray should be initialized to an array and not a string.
So
import axios from "axios";
import React, { useState, useEffect } from "react";
import "../styles/ProductContainer.scss";
import Product from "./Product";
const ProductContainer = () => {
const [productArray, setProductArray] = useState([]);
useEffect(() => {
axios.get("https://fakestoreapi.com/products").then((res) => {
setProductArray(res.data);
});
}, []);
return (
<div className="product-container">
{productArray.map((product) => {
<Product imgUrl={product.image} name={product.name} price={product.price} />;
})}
</div>
);
};
export default ProductContainer;