0

Is this save? will this.props.history push ignore setState since setState is async?

if (id) {
    this.props.history.push(`/edit/${data.id}`)

  this.setState({
    showMsg: 'saved'
  })
}

or I should do this?

if (id) {
  this.setState({
    showMsg: 'saved'
  }, ()=>this.props.history.push(`/edit/${data.id}`))
}
Yunyi Chang
  • 159
  • 1
  • 12
  • Please have a look at [when to use setState callback](https://stackoverflow.com/questions/42038590/when-to-use-react-setstate-callback/42038724#42038724), Also your syntax for setState callback is incorrect in the second case – Shubham Khatri Jul 17 '18 at 07:52
  • @ShubhamKhatri what's wrong with the first one? – Yunyi Chang Jul 17 '18 at 07:53
  • For the first one, since you are using history.push, it will unmount the current component to navigate tothe correct route and within that period if you call setState, it would give you an error saying `Attempting to call setState for an unmounted component`, So you need to make sure that you call setState and then once it is completed call history.push – Shubham Khatri Jul 17 '18 at 07:55

1 Answers1

2

The second parameter of setState method is a callback and it will not accept it as argument.

change this

  if (id) {
      this.setState({
        showMsg: 'saved'
      }, this.props.history.push(`/edit/${data.id}`))
    }

to this

if (id) {
  this.setState({
    showMsg: 'saved'
  },()=> this.props.history.push(`/edit/${data.id}`))
}

Is this save?

Yes when you set a state and once its set; you get through callback. It will push to history after state was set.

Manoz
  • 6,507
  • 13
  • 68
  • 114
  • I'm asking it is save for the first block of code, not the second one, I know second one make sense. – Yunyi Chang Jul 17 '18 at 07:54
  • @YunyiChang, No it will not save since you are pushing history and in the meantime that component should have been unmounted. – Manoz Jul 17 '18 at 08:34