productList is an array from the redux state, it's the actual array of products. The cart is an array of product ids. I set the productsToRender to store the products ids and then extract them in the the ids variable. In the useEffect I am looking for the actual products that are in the cart. The main problem is that my if statements do not check properly if the variables are not empty arrays or null or undefined, the code starts to execute the very bottom of the jsx where I am actually using the products state variable which is [undefined, undefined, undefined]. Therefore throwing an error.
Updated the useEffect , the productList is [] and the if statement does not check it correctly, it prints
Effect, after if statement [productList] []
const ProductList = ({ productList, cart }) => {
const [products, setProducts] = React.useState(null)
const productsToRender = cart.products
const ids = productsToRender.map(p => p.productId)
React.useEffect(() => {
console.log("Effect [ids]", ids);
console.log("Effect [productList]", productList);
if (!productList || productList.length === 0) {
console.log("Effect, after if statement [productList]", productList);
let ps = ids.map(id => {
let product = productList.find(p => p.id === id)
if (Product) return product
})
setProducts(ps)
}
}, [productList])
if (!products || products.length === 0) {
console.log("Products null or l0", products);
return <Loading />
}
... some more jsx
const mapStateToProps = state => {
return { productList: state.products };
};
export default connect(
mapStateToProps,
{}
)(ProductList);
CodePudding user response:
Things to look for
ps = ps.filter(p => p === undefined)should beps = ps.filter(p => p !== undefined)p.id === idp.id and id should be of same type.
If this doesn't solve the problem please post the data contained in each of the props.
CodePudding user response:
if (!productList || productList.length === 0) should be
if (!productList || productList.length !== 0)
CodePudding user response:
Your if statement states
!productsList || productList.length === 0
which essentially means that the if statement code is going to run if your productsList array is null or has length 0 meaning empty which I reckon is the case with your productsList array.
Thus, changing the if statement to:
!productsList || productList.length !== 0 should fix the problem.
Thanks,
Arjis Chakraborty.
