Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why do I get NaN as result of operation perfomed on three valid numbers?

the following piece of Code returns NaN eventhough the values forming the expression are all valid numbers. I am quite confused and frustrated xD. What is my error here?

private getAllData = (res: any) => {
    this.setState({ priceBinance: res["binance"]["price"] })
    this.setState({ volumeBinance: res["binance"]["volume"] })
    this.setState({ highBinance: res["binance"]["high"] })
    this.setState({ lowBinance: res["binance"]["low"] })

    this.setState({ priceCrypto: res["crypto"]["price"] })
    this.setState({ volumeCrypto: res["crypto"]["volume"] })
    this.setState({ highCrypto: res["crypto"]["high"] })
    this.setState({ lowCrypto: res["crypto"]["low"] })

    this.setState({ priceKraken: res["kraken"]["price"] })
    this.setState({ volumeKraken: res["kraken"]["volume"] })
    this.setState({ highKraken: res["kraken"]["high"] })
    this.setState({ lowKraken: res["kraken"]["low"] })

    // THIS IS WHERE IT FAILS
    this.setState({ priceAverage: (this.state.priceBinance! + this.state.priceCrypto! + this.state.priceKraken!) / 3.0 })
    this.setState({ voulumeAverage: (this.state.volumeBinance! + this.state.volumeCrypto! + this.state.volumeKraken!) / 3.0 })
    this.setState({ highAverage: (this.state.highBinance! + this.state.highCrypto! + this.state.highKraken!) / 3.0 })
    this.setState({ lowAverage: (this.state.lowBinance! + this.state.lowCrypto! + this.state.lowKraken!) / 3.0 })
  }

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

setState is an asynchronous operation, meaning once you set a value to the state, it need not immediately update the state and, also you are force unwrapping the state values using !, for which you are getting NaN implies that the state value has not yet been updated when you’re trying to access the state value, there are two approaches to solving this:

  1. Invoke a callback once the state is updated(Not recommended, as you’ve to do it for every state value).

  2. Use res property to get hold of the value directly and perform the desired operation.

this.setState({ priceAverage: (res["binance"]["price"] + res["crypto"]["price"] +res["kraken"]["price"]) / 3.0 })
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading