Search code examples
reactjsonclickstatesetstatereact-lifecycle

React state not changing after setState


class App extends React.Component{
  constructor() {
    super();
    this.state = {
      route: "Branches",
      adding: false,
      user: '',
      table: [],
      Branche: '',
    }
  }

  OnAccessBranch = (event) => {
    this.setState({Branche: event.target.name, route: event.target.id})
    console.log(this.state)
    this.CheckTable(this.state.route)
    console.log(this.state)
}


  CheckTable = (route) => {
    switch(route){
        case "Guichets": 
            this.setState({table: Guichets})
            console.log(this.state.route)
            break;
        case "Services": 
            this.setState({table: Services})
            console.log(this.state.route)
            break;
        case "Branches": 
            this.setState({table: Branches})
            console.log(this.state.route)
            break;
        default: 
            this.setState({table: Branches})
    }
  }

I have a button in the app that executes OnAccessBranch whenever clicked but for some reason the first console.log() shows the old state even though there's a setState right before. I noticed that I have to click the button two times in order for it to print the correct new State. I'm not sure whether it's a React lifecycle problem that I'm not getting or if it's browser related but whenever I have button that changes state I always have to click it two times.


Solution

  • setState() doesn't immediately update the state, meaning you are console logging the existing value without allowing the state to change. When you click the button for the second time, the state has finally changed so the console.log captures the right value, making it seem like setState only works on the second time.

    Consider using a callback function like so:

    this.setState({table: Guichets}, function () {
        console.log(this.state.route);
    });