2

I am new to ReactJS. On my index page, the initial state of loginState & modalStatus is false. I am trying to change modalStatus to true inside componentDidMount().

class Home extends Component {
  constructor(props) {
    super(props);
    this.state = {
      isLoggedIn: true,
      modalStatus: false,
    };
  }

  componentDidMount() {
    if(this.state.isLoggedIn) {
      console.log(this.state.modalStatus);
      this.setState({ modalStatus: true});
      console.log(this.state.modalStatus);
    }  else {
        console.log(this.state.modalStatus);
    }
  render() {
    return (
      <>
       <h1>Hello</h1>
      </>
    );
  }
}

But my console is printing false for both modalStatus even after setState. Is there anything I am doing wrong? Please guide me. I would appreciate any helps.

TEMP
  • 235
  • 2
  • 7
  • 17

2 Answers2

5

SetState is asynchronous so when you do setState the modifies value won’t be available immediately. In order to see updated state value

Change

  componentDidMount() {
if(this.state.isLoggedIn) {
  console.log(this.state.modalStatus);
  this.setState({ modalStatus: true});
  console.log(this.state.modalStatus);
}  else {
    console.log(this.state.modalStatus);
}
}

To

 componentDidMount() {
if(this.state.isLoggedIn) {
  console.log(this.state.modalStatus);
  this.setState({ modalStatus: true}, () => {
       console.log(this.state.modalStatus);
  });
}  else {
    console.log(this.state.modalStatus);
}
}
Hemadri Dasari
  • 32,666
  • 37
  • 119
  • 162
0

Changes made via setState() will not be immediately reflected. It is an asynchronous function. Try logging it inside render() you can see the new value.

NOTE: you should not leave the console.log() inside render function, as it will impact performance

obai
  • 399
  • 5
  • 14