简体   繁体   中英

TypeError: Cannot read properties of undefined (reading '_id') cart add

Sometimes when i try to add 2 element to cart i have this problem, but if i refresh and try to make same things, this error doesn`t appear:

Unhandled Runtime Error TypeError: Cannot read properties of undefined (reading '_id') context\StateContext.js (17:61) @ eval 15 | 16 | const onAdd= (product, quantity) => {

17 | const checkProductInCart = cartItems.find((item) => item._id === product._id ); | ^ 18 |
19 | setTotalPrice((prevTotalPrice) => prevTotalPrice + product.price * quantity ); 20 | setTotalQuantities((prevTotalQuantities) => prevTotalQuantities + quantity );.

Thanks

Hey @Florin it would be super helpful to get a little more information about your environment. Are you running React in any framework like NextJS or is you project Create React App? Is this error consistent with development and production environments? Also where is your data coming from? Redux, GraphQL, or maybe just a fetch or axios call?

My best guess to what the issue is from your post is maybe on the first render there is a pause before the data is coming back from the API or promise so its null or undefined for a moment then when you refresh it is grabbing the data from the cache therefore there is no delay.

Perhaps adding a little check onto your items would solve the issue?

I usually do something like this in my code:

const checkProductInCart = cartItems && cartItems.find((item) => item._id === product._id );

This way the iterator find unless cartItems is truthy (not undefined or null).

Let me know what you think and if this does not work maybe with more details I can give you some more debugging advice.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM