will mannix
will mannix

Reputation: 153

Having trouble setting the state in a promise

I have a series of promises in my componentDidMount() function. In the values.then(function(result) promise, I am trying to set the state. I get this error Unhandled Rejection (TypeError): Cannot read property 'setState' of undefined but researched this error and I need to bind my promise using an arrow function to give it access to the this keyword.

componentDidMount() {
        let general = {};
        let values = [];
        //gets selected setting form schema
        getSettingsForms().then((response) => {
            this.setState({settingsForms: response});
            general = response[this.state.selectedSetting];
        }).then(response => {
            values = getSettingsConfig(this.state.selectedSetting, general);
            values.then(function(result) {
                this.setState({
                    formSchema: result[1],
                    selectedSetting: this.state.selectedSetting,
                    settings: result[0]

                })

            })
        })
    }

The problem is that I don't know where to put the arrow function on this sort of promise. Anywhere I put it, I get an error saying Unexpected token, expected "{" and then when I try put the curly brace in, I get another error.

componentDidMount() {
        let general = {};
        let values = [];
        //gets selected setting form schema
        getSettingsForms().then((response) => {
            this.setState({settingsForms: response});
            general = response[this.state.selectedSetting];
        }).then(response => {
            values = getSettingsConfig(this.state.selectedSetting, general);
            values.then(function(result) => {
                this.setState({
                    formSchema: result[1],
                    selectedSetting: this.state.selectedSetting,
                    settings: result[0]

                })

            })
        })
    }

What is the correct way to put in this arrow function to the values.then(function(result) promise so that I can then set the state? `

Upvotes: 0

Views: 31

Answers (1)

Travis James
Travis James

Reputation: 1939

Just like the other two arrow functions you are using:

componentDidMount() {
        let general = {};
        let values = [];
        //gets selected setting form schema
        getSettingsForms().then((response) => {
            this.setState({settingsForms: response});
            general = response[this.state.selectedSetting];
        }).then(response => {
            values = getSettingsConfig(this.state.selectedSetting, general);
            values.then(result => {
                this.setState({
                    formSchema: result[1],
                    selectedSetting: this.state.selectedSetting,
                    settings: result[0]

                })

            })
        })
    }

Upvotes: 1

Related Questions