I am using js Object and in this object I have 3 section of data: first section (New Arrival) second section (Best Seller) and third section (Special Offer), when I use array.map() to loop the data this error happen
I saw many problems here like mine but no solution be right with me
and this is the code
import ProductItem from './ProductItem';
import {getAll} from '../../api/product';
class Products extends Component {
state ={
products :[]
};
componentDidMount(){
getAll().then(data =>{
this.setState({
products :data
})
});
}
render() {
return (
<div className="container">
<div className="head-with-border"><h2>New Arrival</h2></div>
<div className="products">
{this.state.products.bestSeller.map(product =>
<div className={"product"} key={product.id}>
<ProductItem product={product}/>
</div>
)}
</div>
</div>
)
}
}
export default Products;
You have a race condtion in your code. The initial render happens befor you upload the data with fetch.
import ProductItem from './ProductItem';
import {getAll} from '../../api/product';
class Products extends Component {
state ={
products :[]
};
componentDidMount(){
fetchData()
}
const fetchData = async () => {
let data = await getAll()
this.setState({
products :data
})
}
render() {
return (
<div className="container">
<div className="head-with-border"><h2>New Arrival</h2></div>
<div className="products">
{(this.state.products.bestSeller
? this.state.products.bestSeller
: []
).map(product =>
<div className={"product"} key={product.id}>
<ProductItem product={product}/>
</div>
)}
</div>
</div>
)
}
}
export default Products;
You need to check for the default empty state:
import ProductItem from './ProductItem';
import {getAll} from '../../api/product';
class Products extends Component {
state ={
products: {}
};
componentDidMount(){
getAll().then(data =>{
this.setState({
products :data
})
});
}
render() {
const { bestSeller } = this.state.products;
return (
<div className="container">
<div className="head-with-border"><h2>New Arrival</h2></div>
<div className="products">
{bestSeller && bestSeller.map(product =>
<div className={"product"} key={product.id}>
<ProductItem product={product}/>
</div>
)}
</div>
</div>
)
}
}
export default Products;
I also changed your default product state to an empty object instead of a array to align it with the data structure you are working with.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.