Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Cannot read properties of undefined (reading 'map') i can't use my variable again

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)
 : [];
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading