1

Unable to this.setState() with fetch() response

Did fetch() inside form submit event handler, but unable to set the state from the fetch() callbacks

TypeError: Cannot read property 'setState' of undefined

    ...
    constructor(props) {
        super(props);
        this.state = { deviceName: '', devices: [] };
        this.handleChange = this.handleChange.bind(this);
        this.handleSearchDevice = this.handleSearchDevice.bind(this);
    }

    componentWillMount() {
        this.setState({
            devices: this.props.devices
        });
    }

    componentDidMount() {
    }

    componentWillReceiveProps(nextProps) {
        this.setState({
            devices: nextProps.devices
        });
    }

    handleChange(event) {
        this.setState({deviceName: event.target.value });
    }
    handleSearchDevice(event) {
        console.log('Searching '+this.state.deviceName)
        event.preventDefault();

        //Get data from API
        const url = 'device/name'
        const data = { deviceName:this.state.deviceName}
        fetch(url, { method: 'POST',
            body: JSON.stringify(data),
            headers:{ 'Content-Type': 'application/json' }
        }).then(res => {
            res.json().then(function(data) {
                console.log('API Response: '+JSON.stringify(data))
                try {
                    this.setState({devices: data.resp, deviceName: data.deviceName})
                } catch(err) {
                    console.log('catch ' + err.stack)
                    this.callback1(data)
                }
            });
        }).catch(error => {
            console.error('Error:', error)
        }).then(response => {
            console.log('Success:', response)
        });
    }
    callback1(data) {
        this.setState({devices: data.resp, deviceName: data.deviceName})
        console.log(data)
    }

    render() {
        ...
    }

    componentDidUpdate(prevProps) {
    }

    ...

I expect to set the state from callbacks inside the event handler Error screenshot

Visv M
  • 431
  • 4
  • 13
  • Possible duplicate: https://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-inside-a-callback – Rallen May 09 '19 at 06:59

1 Answers1

0

That is because you have not bound the function callback1 to this. So in your constructor you should bind it the same way you bind your other functions.

An alternative way is to make callback1 an arrow function instead so that it does not have to be bound. That would look like this:

callback1 = () => {
    this.setState({devices: data.resp, deviceName: data.deviceName})
    console.log(data)
}
ApplePearPerson
  • 4,209
  • 4
  • 21
  • 36
  • That worked. Much appreciated @ApplePearPerson for the clear answer ``` res.json().then((data) => { console.log('API Response: '+JSON.stringify(data)) try { this.setState({devices: data.resp, deviceName: data.deviceName}) ``` – Visv M May 09 '19 at 07:22