0

I am trying to make a text box auto focus.

However, I the setState is being called too late it seems.

It is being called within Popup.show. I created a button to console.log the state, and it does seem to be set to true but it must happen too late.

How can I get setState to be called as the Popup.show happens?

class Dashboard extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      focused: false,
    };
  }
  onClick = (event) => {
    console.log('Says focussed FALSE', this.state.focused)
    this.setState({ focused:true });
    Popup.show(<div>
      <SearchBar
        autoFocus
        focused={this.state.focused}
      />
      <button onClick={this.checkState}>It says TRUE here</button>
    </div>, 
     console.log('Says focussed FALSE still', this.state.focused),
   { animationType: 'slide-up'});
  };
  checkState = (e) =>{
    console.log(this.state)
  }
  render() {
    return (
      <div style={{ padding: '0.15rem' }}>
      <Button onClick={this.onClick.bind(this)}>Open & Focus</Button>
    </div>);
  }
}
Ycon
  • 1,830
  • 3
  • 27
  • 56
  • 1
    Possible duplicate of [Why calling setState method doesn't mutate the state immediately?](https://stackoverflow.com/questions/42593202/why-calling-setstate-method-doesnt-mutate-the-state-immediately) – Mayank Shukla May 27 '17 at 09:49

2 Answers2

2

Always remember that setState won't execute immediately. If you want Popup.show() after setState, you can use a callback:

this.setState({ focused: true }, () => {
  Popup.show(...)
})

And you are already using arrow functions, you don't need the .bind(this) in your render function.

CodinCat
  • 15,530
  • 5
  • 49
  • 60
0

setState doesn't immediate set the state

From: https://facebook.github.io/react/docs/react-component.html#setstate

Think of setState() as a request rather than an immediate command to update the component. For better perceived performance, React may delay it, and then update several components in a single pass. React does not guarantee that the state changes are applied immediately.

Changing your setState to something like

this.setState({ focused: true }, () => {
    Popup.show(<div>
    <SearchBar
    autoFocus
    focused={this.state.focused}
    />
    <button onClick={this.checkState}>It says TRUE here</button>
    </div>)
});
user2340824
  • 2,142
  • 2
  • 15
  • 19
  • I think this has worked, my the `focused={this.state.focused}` is still not reacting to. Is there any reason why this might be? – Ycon May 27 '17 at 09:58
  • If you changed it to: `this.setState({ focused: true }, () => console.log(this.state.focused));` does it say true within the console? If it does, the issue may lie within your SearchBar – user2340824 May 27 '17 at 10:05