Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Axios ReactJS - Cannot read property 'setState' of undefined

I am getting an error "TypeError: Cannot read property 'setState' of undefined" while doing a simple thing in ReactJS. I am trying to use axios to fill input with response data. So far without success. I am very new to both axios and ReactJs so it might be something very simple I overlooked?

I would expect "RESPONSE TEXT" to show up in the input field in the form after the TypeError is fixed.

This is my component:

class BasicInfoBlock extends React.Component {
    constructor(props) {
        super(props);

        this.state = { name : "EventTestName" };
    }

    componentDidMount() {
        axios
        .get(getBaseUrl()+`get`)
        .then(function (response) {
            this.setState({name: "RESPONSE TEXT"});
            //this.setState({name: response.data.name});
        })
        .catch((e) => 
        {
            console.error(e);
        });
        //this.setState({});
    }


    render(){
        return(
                <form className="form-horizontal">
                    <div className="form-group">
                        <label htmlFor="eventName" className="col-sm-2 control-label">Name</label>
                        <div className="col-sm-10">
                        <input type="text" id="eventName" className="form-control" placeholder="Event name" defaultValue={this.state.name}/>
                        </div>
                    </div>
                </form>
            );
    }
}

Thank you for your help

edit: this is not a duplicate question, this questions relates to 'this' not being available in callback. Question selected as duplicate is related to bind.

like image 208
rluks Avatar asked Dec 08 '16 15:12

rluks


People also ask

Can't access property setState this is undefined?

The "cannot read property 'setState' of undefined" error occurs when a class method is called without having the correct context bound to the this keyword. To solve the error, define the class method as an arrow function or use the bind method in the classes' constructor method.

Can we use setState in loop?

No! This method is called whenever there is a re-render. So, if we use setState() here that triggers re-render again which leads to an infinite loop. never use setState() here.


1 Answers

In your Promise's then method, this will no longer refer to the component. You could fix by using an arrow function like this:

componentDidMount() {
  axios
  .get(getBaseUrl()+`get`)
  .then((response) => {
    this.setState({name: "RESPONSE TEXT"});
    //this.setState({name: response.data.name});
  })
  .catch((e) => 
  {
    console.error(e);
  });
  //this.setState({});
}
like image 111
Ben Nyberg Avatar answered Oct 14 '22 05:10

Ben Nyberg