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 :
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:
-
Invoke a callback once the state is updated(Not recommended, as you’ve to do it for every state value).
-
Use
resproperty 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 })