I have these configurations in my products component:
import axios from "axios";
import React, { useEffect } from "react";
import { useDispatch } from "react-redux";
import { connect } from "react-redux";
import productsAction from "../redux/actions/productsAction";
import { FETCH_PRODUCTS } from "../redux/actions/types";
function products({ products }) {
const dispatch = useDispatch();
useEffect(() => {
axios.get("http://localhost:8197/Plant/GetPlant").then(({ data }) =>
dispatch({
type: FETCH_PRODUCTS,
payload: data,
})
);
}, []);
return (
<div>
{products.map((product, index) => (
<h1 key={index}>{product.title}</h1>
))}
</div>
);
}
export const mapStateToProps = (state) => {
return {
products: state.products.products,
};
};
export default connect(mapStateToProps)(products);
Everything is okay, but when I run the project, It throws an error:
TypeError: Cannot read properties of undefined (reading 'map')
And when I inspect the project by redux devtools, the products array is equal to [].
How can I fix error?
CodePudding user response:
your code is accessing products before it is initialized. What you could do now is conditional rendering.
<div>
{products && products.map((product, index) => (
<h1 key={index}>{product.title}</h1>
))}
</div>
CodePudding user response:
You are rendering the products before the API call which will definitely return undefined.
So instead write
{
products?.map((product, index) => (
<h1 key={index}>{product.title}</h1>
))
}
or
{
!!products && products.map((product, index) => (
<h1 key={index}>{product.title}</h1>
))
}