I try to render a list with products but unfortunely the list updates too late. The Products List is empty. When I execute it the second time it works. Is there any solution?
Thank you very much!
export const Products = (props) => {
const [products, setProducts] = useState([]);
const [ListProducts, setListProducts] = useState([]);
const [List, setList] = useState([]);
const loadProducts = async (categorieid) => {
const apiProducts = await axios.get(`${url}/products/${categorieid}`);
setProducts(apiProducts.data.body);
};
const mapData = async () => {
if (products && products.length) {
products.map((product) =>
ListProducts.push(
<ProductCard product={product} key={product.id} />
)
);
setListProducts(ListProducts);
} else {
List.push(
<div className="column">
<span className="title has-text-grey-light">
No products found!
</span>
</div>
);
}
const renderListProducts = () => {
return <div className="container">{ListProducts}</div>;
};
const writeCategory = async (kategorieId) => {
await loadProducts(kategorieId);
await mapData();
await renderListProducts();
};
}
CodePudding user response:
your mistake is in here
const writeCategory = async (kategorieId) => {
await loadProducts(kategorieId);
await mapData();
await renderListProducts();
};
setProducts is called at the end of loadProducts, but it is not necessary will update the state before mapData will be called.
The solution is to use useEffect as the trigger for next function
const writeCategory = async (kategorieId) => {
loadProducts(kategorieId);
};
useEffect(() => { products.length && mapData(), [products.length] }
and so on for the third function renderListProducts
BTW in
products.map((product) =>
ListProducts.push(
<ProductCard product={product} key={product.id} />
)
)
you're modifying ListProducts state outside setState, consider do something like
const temp = products.map((product) => <ProductCard product={product} key={product.id} /> )
setListProducts(temp)
instead
