Search code examples
reactjsreduxfetch

I got undefined data while getting it from useSelector in react


I am making an e commerce website for which , I am using react and redux for frontend and express as the server . I got undefined when I tried to access the data of the redux store from useSelector hook , but I got the data when I console.log() it in the action . Please help I have been struggling with this from the last two days.

I am getting this error : TypeError: Cannot read properties of undefined (reading 'map')

This is My code for HomeScreen

const dispatch = useDispatch();
const productList = useSelector((state) => state.productList);
const { products } = productList;
console.log("Product List : ", products);

useEffect(() => {
  dispatch(listProducts());
}, [dispatch]);

return (
 <div>
   {products.map((data, id) => {
     return (
       <div className="product_div" key={id}>
         <Products data={data} />
       </div>
     );
   })}
 </div>

);

This is For productAction:

import {
 PRODUCT_LIST_FAILURE,
 PRODUCT_LIST_REQUEST,
 PRODUCT_LIST_SUCCESS,
} from "../Constants/productConstants";

export const listProducts = () => async (dispatch) => {
 dispatch({ type: PRODUCT_LIST_REQUEST });
 try {
  const res = await fetch("/products", {
    method: "GET",
    headers: {
      "Content-Type": "Application/Json",
    },
  });
const data = await res.json();
console.log("Product Data : ", data);
dispatch({ type: PRODUCT_LIST_SUCCESS, payload: data });
} catch (error) {
  dispatch({ PRODUCT_LIST_FAILURE, payload: error });
}

};

**I got the data here **

But it shows porducts as undefined in HomeScreen.js


Solution

  • Tro to add an undefined check in the HomeScreen component and return a loading message in it.
    This should avoid causing a crash in your application, and will render the data once they are ready.

    ...
    
    if (!products) {
        return <div>Loading products...</div>
    }
    
    return (
     <div>
       {products.map((data, id) => {
         return (
           <div className="product_div" key={id}>
             <Products data={data} />
           </div>
         );
       })}
     </div>