简体   繁体   中英

React setting state from an axios response

I am attempting to update state with information returned from an axios POST call. I am getting an error saying TypeError: Cannot read property 'setState' of undefined . It sounds to me like this is not usable from a API response.

submitData= () => {
        axios.post("url", this.props.data)
        .then(function (result) {
            console.log(result,'success');
            this.setState({
                ...this.state,
                id: result.data.id
            })
          })
          .catch(function (err) {
            console.log(err, 'fail');
          });

    }

I can console log result.data.id and it is the correct id. I am doing this all client side and I do not want to build out a server or use a reducer.

use arrow function in your callback like this :

submitData= () => {
        axios.post("url", this.props.data)
        .then((result) => {
            console.log(result,'success');
            this.setState({
                ...this.state,
                id: result.data.id
            })
          })
          .catch(function (err) {
            console.log(err, 'fail');
          });

    }

You can also use async/await syntax and pass data as argument for greater flexibility/reusability. Try:

submitData = async (data) => {
    try {
        const result = await axios.post('url', data);
        console.log('Success', result);
        const { id } = result.data;
        this.setState({
            ...this.state,
            id,
        });
    } catch (err) {
        console.log('Failure', err);
    }
}

Try making the .then an anonymous function to bind this .

submitData= () => {
    axios.post("url", this.props.data)
    .then((result) => {
        console.log(result,'success');
        this.setState({
            ...this.state,
            id: result.data.id
        })
      })
      .catch((err) => {
        console.log(err, 'fail');
      });
}

In the callback function this would be undefined (that's how this in js works). If you want an easy fix, just use arrow functions

submitData= () => {
        axios.post("url", this.props.data)
        .then(result => {
            console.log(result,'success');
            this.setState({
                ...this.state,
                id: result.data.id
            })
          })
          .catch(function (err) {
            console.log(err, 'fail');
          });
    }

read more about this https://hackernoon.com/javascript-es6-arrow-functions-and-lexical-this-f2a3e2a5e8c4

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM