I have the following order and I want to map through the order items and shippingAddress .
{message: "New Order Created",…}
message: "New Order Created"
order: {orderItems: [{name: "4Formaggi", quantity: 1, image: "pics/4formagi.jpg", price: 30,…},…],…}
createdAt: "2022-06-02T02:19:26.124Z"
isDelivered: false
isPaid: false
orderItems: [{name: "4Formaggi", quantity: 1, image: "pics/4formagi.jpg", price: 30,…},…]
0: {name: "4Formaggi", quantity: 1, image: "pics/4formagi.jpg", price: 30,…}
1: {name: "4Stagioni", quantity: 1, image: "pics/4stagioni.jpg", price: 30,…}
paymentMethod: "paypal"
shippingAddress: {fname: "Marius-Daniel Ciufu", city: "Baicoi", postal: "105200", county: "Prahova", address: "Baicoi"}
address: "Baicoi"
city: "Baicoi"
county: "Prahova"
fname: "Marius-Daniel Ciufu"
postal: "105200"
totalPrice: 60
updatedAt: "2022-06-02T02:19:26.124Z"
user: "6297ef1744555d10ed5a704b"
__v: 0
_id: "62981e2e4fa20d980c6f3a29"
I've tried with order.orderItems.map((item) => ...) but it's not working. I'm receiving the following errors :
Order.js:54 Uncaught TypeError: Cannot read properties of undefined (reading 'fname')
react-dom.development.js:18525 The above error occurred in the <Order> component:
If anybody have a hint please tell me
CodePudding user response:
Your issue is that right when your component is mounted order
is just an empty object so there is nothing for you to map over. There are a few ways you could go about resolving this but for your example I would recommend adding in some sort of loading state.
if(!order._id) {
return '...loading';
}
return (
<div className="placeorder-container-items">
// The rest of your component
</div>
)
This means that while your api call is happening you would be seeing the loading text but once its done and there is something in order than everything in your second return will show.
Another alternative is in your useReducer have order as null and just do the same thing as above but just for the whole order object.
const [{ order }, dispatch] = useReducer(reducer, {
order: null,
});
if(!order){
return '...loading';
}