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;
CodePudding user response:
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)
: [];
CodePudding user response:
The map function is only used to iterate an array. If any other type of data is been sent into products then use the following exception to not produce a crash or error.
Syntax
array.map((item, index) => {
//code
})
Your representation
<div className="row center" >
{products?.map((product) => (
<Product key={product._id} product={product} ></Product>
))}
</div>
CodePudding user response:
The thing you are missing is short circuiting. When you use redux thunk as a middleware or any asynchronous way to fetch the data from server,then you have to make sure each node of the object which you want to render should be found. It is because at the very first miliseconds the data is not already fetched but react tends to render the data which will obviously null or undefinded as the data is not fetched yet.
This can be solved in two different ways with short circuiting.
1. Pass the deepest node or make sure the length of products is not 0 by passing it in a dependency array as:
useEffect(()=> {
dispatch(listProducts());
}, [dispatch,products?.length])
2.
{products?.products.map((product) => (
<Product key={product._id} product={product} ></Product>
))}
for more refrerence,you can look at:short-circuiting-evaluation in javascript