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

Viewed 24

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 );.
1 Answers

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.

Related