Reputation: 3538
I want to have multiple callbacks after running this.setState()
This code works and this work is printed
.
savePitch(e){
this.setState({savedPitches: [...this.state.savedPitches, this.state.addNewPitch]})
this.setState({addNewPitch: {
id: this.state.addNewPitch.id + 1,
pitchName: '',
shortCut: '',
subject: '',
pitch: ''
}},
() => {console.log('this worked')},
)
this.toggleNewPitchForm()
}
However if I want to have two functions run, I tried below but it doesn't work as expected.
savePitch(e){
this.setState({savedPitches: [...this.state.savedPitches, this.state.addNewPitch]})
this.setState({addNewPitch: {
id: this.state.addNewPitch.id + 1,
pitchName: '',
shortCut: '',
subject: '',
pitch: ''
}},
() => {console.log('this worked')},
() => {console.log('then this worked')},
)
this.toggleNewPitchForm()
}
What changes should I make to make this run as expected?
Upvotes: 2
Views: 4842
Reputation: 1738
Just define the method that will call the other methods.
const myMethod = () => {
myMethod1();
myMethod2();
myMethod3();
};
this.setState({addNewPitch: {...}}, myMethod);
Upvotes: 3
Reputation: 1425
Simply call the methods sequentially within an arrow function:
this.setState(..., () => {
(() => { console.log('one') })()
(() => { console.log('two') })()
}
Upvotes: 6