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