Skip to content
Advertisement

Why do I get NaN value in react?

Whilst I am doing cart in react, I have no idea why I keep getting NaN value – only from a specific object data.

When I have the following data list:

#1 ItemsList.js

JavaScript

And the following code, please look at the comment line.

#2 Goods.jsx

JavaScript

What should I do to solve NaN? There seems to be no way to make that value as int in this case. Or do you see any problem from the above code block?

Edited

Sorry for confusing you. Here are the additional code related.

#3. DataContext.js (where cartItems state exists)

JavaScript

Advertisement

Answer

The issue is in the function you are using to set the initial value of cartItems, more specifically, in the for loop. This line is the culprit: i < ItemsList.length, when in your case, it should be i <= ItemsList.length. Why? because you are not including the last element of ItemsList on the cart object (you are initializing the i counter with 1 and ItemsList‘s length is 6).

So, when you call addItemToCart:

JavaScript

And try to update the value corresponding to the last element of ItemsList which is 6 in cartItems, you’re getting: '6': undefined + 1 because again, you did skip the last element in the for loop. This results in NaN.

You also have the option of initializing i with 0 and preserve this line: i < ItemsList.length, or:

JavaScript
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement