val_ya
val_ya

Reputation: 99

Can I set state property as a callback?

Is it OK to set state in a callback? The code actually works but I need to know if it is fits good practices on setting state.

this.setState(this.props.onSuccess(data), () => {loading: false})

Upvotes: 0

Views: 68

Answers (3)

Bhushan Patil
Bhushan Patil

Reputation: 105

// WRONG

this.setState({ count: this.state.count + props.count})
doSomething(this.state.count)

// RIGHT

this.setState((prevState,props) => ({counter: prevState.count + props.count}))
  • Dont rely on current state when computing

Upvotes: 2

Bhojendra Rauniyar
Bhojendra Rauniyar

Reputation: 85545

You probably want to set the state on the hook itself:

onSuccess(data) {
 // ...
 this.setState({loading: false})
}

Upvotes: 3

rrd
rrd

Reputation: 5957

Would this be more effective:

this.props.onSuccess(data) && this.setState({ loading: false });

I don't think the pattern you have used is something very common at all.

Upvotes: 1

Related Questions