Halfway done calculator, every other time I get NaN

If anyone would be so kind to check out my calculator here https://codepen.io/seth-alan-burleson/pen/Exgjqdr?editors=0111 I’m having an issue where when I hit equals, it gives me ‘NaN’ but if i hit it a second time, the correct result comes up, then another NaN, then another result which is wrong (kind of, but thats a known issue)

Can someone help me figure out where the NaN is coming from?

hey @sbrevolution5,

this is because your adding to state then trying to use that state in the same function call, so this.state.secondNum doesn’t exist untill the second call, if you try using the displayNum instead you will see what i mean,

 case '+':
        result = parseFloat(this.state.firstNum) + parseFloat(this.state.displayNum)
1 Like

Makes sense, followup question, Does this mean I shouldn’t set state in the same function I plan on using it? What if I split it in 2 like this:
prepcalc(){ setState(for secondNum) calc()}
where calc is my current function?

@sbrevolution5, you can use a callback on setState like this

this.setState({secondNum: this.state.displayNum}, this.next)

next() {
//you can use updated state in this function

so you can use the updated state once its been updated.

1 Like