Reputation: 189
I'm new to React and I've created an app using the create-react-app. I have a Golang HTTP server and I am sending a GET request using fetch, receiving a JSON in response. This part works perfectly. The problem arises with wanting to render this JSON. Right now I don't care for formatting. I just want to be able to print it.
With the this.setState line I get an error:
Unhandled Rejection (TypeError): Cannot read property 'setState' of undefined
I've seen a lot of questions here on Stack Overflow and on other websites but I can't find any explanation for why this is happening.
constructor(props) {
super(props);
this.state = {
siteData: []
};
}
componentDidMount() {
console.log("Send GET request to Go server")
fetch("http://localhost:8080/site", {
method: "GET",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
'Access-Control-Allow-Origin': '*',
}
}).then(function(response) {
if (response.status === 200) {
response.text().then(function(data) {
console.log("Get response data: " + data);
console.log(response);
//siteData = JSON.parse(data);
this.setState({
siteData: JSON.parse(data)
});
});
}
})
}
Upvotes: 0
Views: 205
Reputation: 8522
Inside the callback functions of the promises this
is not the same as the this
of react component.
Use Arrow function
in the callback to propagate the context of the react component to the callback function.
<your_code>.then(response => {
if (response.status === 200) {
response.text().then(data => {
console.log("Get response data: " + data);
console.log(response);
//siteData = JSON.parse(data);
this.setState({
siteData: JSON.parse(data)
});
});
}
})
Upvotes: 2