dropWizard
dropWizard

Reputation: 3538

React passing two functions as a call backs to this.setState

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

Answers (2)

hya
hya

Reputation: 1738

Just define the method that will call the other methods.

const myMethod = () => {
  myMethod1();
  myMethod2();
  myMethod3();
};

this.setState({addNewPitch: {...}}, myMethod);

Upvotes: 3

Sven Tschui
Sven Tschui

Reputation: 1425

Simply call the methods sequentially within an arrow function:

this.setState(..., () => {
    (() => { console.log('one') })()
    (() => { console.log('two') })()
}

Upvotes: 6

Related Questions