Joey
Joey

Reputation: 621

can't pass a value that gets from axios (get request) to my state

can't pass a value that gets from axios (get request) to my state

Just looking for another thread .someone told me that I must bind "this" first

this.sendgetRequest = this.sendgetRequest.bind(this); 

but in my case I already did

not sure what my mistake

class Home extends Component {

    constructor(props) {
        super(props);
        this.state = {

            data : [],
            count : 1


        }
        this.sendgetRequest = this.sendgetRequest.bind(this);
    }

    sendgetRequest(){


        axios.get('https://ywc15.ywc.in.th/api/interview')
        .then(function (response) {
          console.log(response);
          this.setState({ data: response.data })
        })
        .catch(function (error) {
          console.log(error);
        });

}
    render() {

        { this.sendgetRequest() }


        return (
            <div>


            </div>

        );
    };
};


export default Home;

error came after inspect console

TypeError: Cannot read property 'setState' of undefined
    at home.js:30
    at <anonymous>

Upvotes: 0

Views: 209

Answers (1)

linasmnew
linasmnew

Reputation: 3977

You're losing the this binding, use an arrow function in your callback instead.

axios.get('https://ywc15.ywc.in.th/api/interview')
  .then((response) => {
    console.log(response);
    this.setState({ data: response.data })
  })
  .catch((error) => {
    console.log(error);
  });

By the way if you're only calling this method once, I would recommend moving the entire sendgetRequest inside of componentDidMount

componentDidMount() {
  this.sendgetRequest();
}

and getting rid of it inside render.

Upvotes: 3

Related Questions