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?

2 answers

  • answered 2017-11-12 19:51 sventschui

    Simply call the methods sequentially within an arrow function:

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

  • answered 2017-11-12 19:51 hya

    Just define method which will call other methods.

    const myMethhod = () => {
      myMethod1();
      myMethod2();
      myMethod3();
    };
    
    this.setState({addNewPitch: {...}}, myMethod);