0

I'm learning React, and actually don't understand why my state does not change immediately when I press a button, with a click event. I mean, I created a state "test: false", but when I click on my button, I just want to change the state, so I used setState. But the console still shows me the "false" when I click for the first time.

Here's a Codesandbox to illustrate my example.

import React from "react";
import "./styles.css";

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      test: false
    };
    this.display.bind(this);
  }
  display() {
    this.setState({
      test: true
    });
    console.log(this.state.test)
  }
  render() {
    return (
      <div className="App">
        <button onClick={() => this.display()}>Click me!</button>
      </div>
    );
  }
}

export default App;

I also want to show "Hello" if state is true and "Goodbye" if the state is false. Can anyone help me, please?

Deep Kakkar
  • 5,831
  • 4
  • 39
  • 75
Laurie Vince
  • 123
  • 2
  • 2
  • 8

2 Answers2

2

I have checked your code and found you are doing mistake there.

As setState() is async. One easy way to handle that is to give it a callback. To print the state just after the setState(), you need to use the code as follows:

display() {
 this.setState({
  test: true
 }, console.log(this.state.test));
}

and about your updated query, you need to use ternary operator as follows:

  render() {
    return (
      <div className="App">
        <button onClick={() => this.display()}>Click me!</button>
        {(this.state.test) ? <p>Hello</p> : <p>Bye</p>}

      </div>
    );
  }
Deep Kakkar
  • 5,831
  • 4
  • 39
  • 75
0

make display an asynchronous function and you can also use es6 for your function deceleration not compulsory though

const display = async _ => {
    await this.setState({
      test: !this.state.test
    });
    await console.log(this.state.test)
  }

//now your button should appear like this

<button onClick={_ => display()}>Click me!</button>
Chukwuemeka Maduekwe
  • 6,687
  • 5
  • 44
  • 67