Hi everyone,
I am having some trouble with two functions executing in order in my React app. After some reading I suspect it has to do with JS being asynchronous. I have tried some things with callbacks that I read about but I can’t seem to get it working.
The two functions are called one after the other when I click a button called “Start”. The idea is that the game will figure out the stats of a character (like their maximum hp), and then give them full hp (their “temporary” hp).
When I do this the numbers come out wrong. However, if I only call calculateStats() in the start button it will set the correct maximum HP. Then, I press a “Test” button with fullHealth() and it correctly sets state to the right temporary hp (equal to the recently calculated max hp).
When I call these both sequentially in the Start button the stats come out like parts of each function were executed, which is why I suspect something with synchronicity but I can’t quite seem to understand how to make it work with callbacks, if that is even the solution. Any help would be appreciated!
this.setState((prevState)=>{return{newGame:false}});
console.log("startbutton "+JSON.stringify(this.state.playerStats))
this.calculateStats()
this.fullHealth()
break
Here is my function for figuring out the max hp and setting it in state.
let playerClass = this.state.playerClass;
let lvl = this.state.playerStats.lvl;
let hp = this.state.playerStats.hp;
let mp = this.state.playerStats.mp;
let equipmentStats = this.state.equipmentStats;
let mainHand = this.state.mainHand;
let offHand = this.state.offHand;
let head = this.state.head;
let body = this.state.body;
let ring = this.state.ring;
let str = mainHand.str+offHand.str+head.str+body.str+ring.str;
let dex = mainHand.dex+offHand.dex+head.dex+body.dex+ring.dex;
let int = mainHand.int+offHand.int+head.int+body.int+ring.int;
let wDmg = mainHand.dmg + offHand.dmg
let sDmg = function(){
switch(true){
case playerClass==="Warrior": return str; break
case playerClass==="Rogue": return dex; break
case playerClass==="Mage": return int; break
default: //nothing
}
}
let def = mainHand.def + offHand.def + head.def + body.def;
let baseDmg = this.state.playerStats.lvl + 1
let tDmg = wDmg + baseDmg + sDmg()
let maxHp = str +(lvl * 2 + 5);
let maxMp = int +(lvl * 2 + 2);
equipmentStats = {dmg:wDmg,def:def,str:str,dex:dex,int:int}
let playerStats = {lvl: lvl, hp: hp, maxHp: maxHp, mp: mp, maxMp: maxMp, baseDmg: baseDmg, tDmg: tDmg}
this.setState((prevState)=>{return{equipmentStats}})
this.setState((prevState)=>{return{playerStats}})
console.log("stats set to "+JSON.stringify(playerStats));
}
Here is the function to set the players temporary hp to their max hp.
fullHealth = function(){
let playerStats = this.state.playerStats
let maxHp = this.state.playerStats.maxHp //this is getting 0 somehow
console.log(maxHp)
playerStats.hp=maxHp
this.setState((prevState)=>{return{playerStats}})
}