Reputation: 99
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
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}))
Upvotes: 2
Reputation: 85545
You probably want to set the state on the hook itself:
onSuccess(data) {
// ...
this.setState({loading: false})
}
Upvotes: 3
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