[Solved] Calculating monthly salary returned NaN in React [closed]


There seems to be one of the reason why you are getting NaN is because you have not initialized netSalary, grossSalary and other variables and as a result they are undefined and when you do something like undefined + 1 => you get NaN.

But why are they undefined?
You might think in your function you updated the state variables before using them, but they are not updated instantaneously not synchronously, so after you have written setTaxRates() and if you try to use the state variables at that moment the state variable have not really updated it’s value, so you will end up using old value, which will be undefined in this case.

Solution?
First initialize the state variables with some default data.
then in your funciton make sure you do not use state variables just after updating them

so your updated code will look something like this.

const salary()=>{
   const [grossSalary,setGross] = useState(0);
   const [taxRate, setTax] =useState(0);
   const [pension, setPension] = useState(0);
   const [netSalary, setNet] = useState(0)
   const calSal =()=>{
     if(grossSalary > 600 && grossSalary<1651){
       let taxR = (grossSalary*0.1)-60;
       let penS= grossSalary*0.7
       netSal = grossSalary-taxR-pension;
       // now update all the states as required
       setTaxRate(taxR);
       setPension(penS);
       setNetSalary(netSal);
     }else{ 
       .......
      }
       .............
   }
 }

2

solved Calculating monthly salary returned NaN in React [closed]