Saturday, March 30, 2019

reactjs - TypeError: cannot read property setState of undefined



I am receiving the data from server but not able to display it on the browser. I am receiving error as:





caught (in promise) TypeError: Cannot read property 'setState' of undefined




import React from 'react';

import axios from 'axios';
class App extends React.Component {
constructor(props){
super(props);
this.state={

posts:'hello',
dos:[]
}

};


componentDidMount() {
axios.get(`http://192.168.1.9:8082`)
.then(function(data) {

console.log(data);
this.setState({dos:data});
});
}

render() {
return (

Hello World!!!

{this.state.posts}



{this.state.dos}



);
}
}

export default App;

Answer



Its a context issue, your mistake is that you didn't bind all the way down to the anonymous function. What you probably want to do is use arrow functions, try this:




componentDidMount() {
axios.get(`http://192.168.1.9:8082`)
.then(data => this.setState({dos:data}););
}


Arrow functions always keep the context of this.



Alternate solution:




componentDidMount() {
axios.get(`http://192.168.1.9:8082`)
.then(function(data) {
console.log(data);
this.setState({dos:data});
}).bind(this);
}

No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...