i had confused by this kind of error despite I had use the self variable products to display all my products but when I try to used it again I can’t catch it note that variable I got it by calling axios by redux.why I didn’t know:
so this is my code:
import React, {useEffect} from "react";
import Product from "../components/Product";
import LoadingBox from "../components/LoadingBox";
import AlertBox from "../components/AlertBox";
import {useSelector, useDispatch} from "react-redux";
import {listProducts} from "../actions/productAction";
const HomePage = () => {
const dispatch = useDispatch();
useEffect(()=> {
dispatch(listProducts());
}, [dispatch])
const productsList = useSelector((state) => state.productsList);
const {products, loading, error} = productsList;
console.log(products)
const categories = products.map((x)=> x.subCategory);
console.log(categories)
return (
<div>
{loading? (<LoadingBox></LoadingBox>):error? (<AlertBox variant="danger" >{error}</AlertBox>):(
<div className="row center" >
{
products.map((product) => (
<Product key={product._id} product={product} ></Product>
))}
</div>
)}
</div>
)
};
export default HomePage;
>Solution :
I bet you initialize your store state.productsList with null, thus you have to check if products really fetched or provide default value for productsList.
const categories = products?.length
? products.map(({subCategory})=> subCategory)
: [];