reactjssetstate

Iam trying to update the state "Experience" but I didn't get updated value. please correct if my code is wrong


am trying to calculate the year of experience so I Initialized state "Experience = 0" and I initialized the current year to the "currentDt" state

    constructor(props){
    super(props);
    this.state = {
        CurrentDt : new Date().getFullYear(),
        DOJ : 0,
        Experience : 0
    }
}

Getting user input for "DOJ" state and updating using setstate()

    GetJoiningDt = (event) =>{
    const DojValue = event.target.value;
   this.setState({
           DOJ :DojValue
       })
}

Below code for subtracting currentYear and DOJ year then trying to update "Experience" state by subtracted value`

    calculateExperience = ()=>{
    alert("Inside_calculateExperience");
    let a = this.state.CurrentDt;
    let b = this.state.DOJ;
    var ExpValue = a - b;        //2021-2015
    alert(ExpValue);             // 6
    this.setState({
        Experience : ExpValue     //0
    })
}

when I alert the value of "ExpValue" it shows value 6 but Inside setstate() its updating 0. and converting states to JSON.

    GetAsJSONData = () =>{
    console.log("JsonData");
    this.calculateExperience();
    let JsonData = {
        Experience : this.state.Experience
    }
    let showdata = JSON.stringify(JsonData);
    document.querySelector('label').textContent = showdata;
    document.write(showdata);

}


    render(){
    return(
        <form>
            <input type="text" value={this.state.DOJ} onChange= 
            {this.GetJoiningDt} placeholder="Year of DOJ" name="fullname" /> 
             <br/>  
            <button type="submit" onClick={this.GetAsJSONData}>Convert 
            Json</button><br></br>
            <label></label>
        </form>
    )
}

Solution

  • You need to consider Async and Await. I made a sandbox version for you.

    import "./styles.css";
    import React from "react";
    
    export default class App extends React.Component {
      constructor(props) {
        super(props);
        this.state = {
          CurrentDt: new Date().getFullYear(),
          DOJ: 0,
          Experience: 0
        };
      }
      GetJoiningDt = (event) => {
        const DojValue = event.target.value;
        this.setState({
          DOJ: DojValue
        });
      };
      calculateExperience = () => {
        alert("Inside_calculateExperience");
        let a = this.state.CurrentDt;
        let b = this.state.DOJ;
        var ExpValue = a - b; //2021-2015
        alert(ExpValue); // 6
        this.setState({
          Experience: ExpValue //0
        });
      };
      GetAsJSONData = async () => {
        console.log("JsonData");
        await this.calculateExperience();
        let JsonData = {
          Experience: this.state.Experience
        };
        let showdata = JSON.stringify(JsonData);
        document.querySelector("label").textContent = showdata;
        document.write(showdata);
      };
    
      render() {
        return (
          <form>
            <input
              type="text"
              value={this.state.DOJ}
              onChange={this.GetJoiningDt}
              placeholder="Year of DOJ"
              name="fullname"
            />
            <br />
            <button type="submit" onClick={this.GetAsJSONData}>
              Convert Json
            </button>
            <br></br>
            <label></label>
          </form>
        );
      }
    }
    

    Please check the link below too see it in action.

    https://codesandbox.io/s/mystifying-water-9w238?file=/src/App.js