Ad

React If/else Returns Before SetState

I want to go through Function ScoreCalc then return the final "primeCount" and setState primeScore to that number.

this.state.animeMax is still empty '' when ScoreCalc() runs in componentWillMount. When I refresh page, primeScore or primeCount changes value. I am guessing it is becuase sometimes "max" state is mounted sometimes not!?

If anyone has ideas, please let me know.

Thank you!

export class Quality extends Component {
    constructor (props) {
        super (props) 
            this.state = {
                primeScore: 0,
                netflixScore: 0,
                huluScore: 0,
                provider:[],
                actionMax:'',
                animeMax:'',
                childrenMax:'',
                comedyMax:'',
                documentaryMax:'',
                horrorMax:'',
                musicalMax:'',
                romanceMax:'',
                scifiMax:'',
                thrillerMax:'',
            }
            this.ScoreCalc = this.ScoreCalc.bind(this);
    }
componentWillMount (){
    axios.get('http://localhost:8001/provider')
        .then(res => this.setState({
            provider: res.data
        },()=>{this.ScoreCalc()}))
    axios.get('http://localhost:8001/provider/actionmax')
        .then(res => this.setState({actionMax: res.data}))
.....10 more axios requests to setState for other "max"....

}
ScoreCalc (){
        let primeCount = 0
            if(this.state.provider[0].primeAction >= this.state.actionMax){
                primeCount += this.props.user.action;
                console.log(primeCount)
            } else {
                primeCount += (this.props.user.action*this.state.provider[0].primeAction/this.state.actionMax)
            }

            if(this.state.provider[0].primeAnime >= this.state.animeMax){
                primeCount += this.props.user.anime;
            } else {
                primeCount += this.props.user.anime*this.state.provider[0].primeAnime/this.state.animeMax;
                console.log(this.state.animeMax) //returns empty ''
                console.log(primeCount) //return infinity
            }

            if(this.state.provider[0].primeChildren >= this.state.childrenMax){
                primeCount += this.props.user.children;
            } else {
                primeCount += this.props.user.children*this.state.provider[0].primeChildren/this.state.childrenMax
            }

         console.log(primeCount); //return infinity
         this.setState({primeScore: primeCount})
}

Ad

Answer

Looks like you have some typos?

In scoreCalc(), you are checking like this:

if(this.state.provider[0].primeAction >= this.actionMax){

i think it needs to be:

if(this.state.provider[0].primeAction >= this.state.actionMax){

The same for the other if's ?

Ad
source: stackoverflow.com
Ad