'paypal check out node js error UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'price' of undefined when i run my code
I have the following code it suppose to send the data to pay pal to process the payment but it keepsgeting this TypeError: Cannot read property 'price' of undefined i have gone through the code but i think the error is occuring "storeItems.get(item.id).price" when i try to get the "items id" for some reson thwe value is nt being seen
this is my request body contains the following array
{"items":[
{"id":"1", "quantity":1},
{"id":"2", "quantity":2},
{"id":"3", "quantity":3},
{"id":"4", "quantity":4}
]}
app.post("/create-order", async (req, res) => {
const request = new paypal.orders.OrdersCreateRequest()
const total = req.body.items.reduce((sum, item) => {
return sum + storeItems.get(item.id).price * item.quantity
}, 0)
console.log(total);
request.prefer("return=representation")
request.requestBody({
intent: "CAPTURE",
purchase_units: [
{
amount: {
currency_code: "USD",
value: total,
breakdown: {
item_total: {
currency_code: "USD",
value: total,
},
},
},
items: req.body.items.map(item => {
const storeItem = storeItems.get(item.id)
return {
name: storeItem.name,
unit_amount: {
currency_code: "USD",
value: storeItem.price,
},
quantity: item.quantity,
}
}),
},
],
})
const order = await paypalClient.execute(request)
})
Solution 1:[1]
The error means that storeItems.get(item.id) in the total function is undefined.
From your comment, storeItems is defined like:
const storeItems = new Map([
[1, { price: 100, name: "Learn React Today" }],
[2, { price: 200, name: "Learn CSS Today" }],
])
So the issue must come from the item. Either it does not have an id property, or it is undefined, or its id property does not match any entry in your map.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Ben |
