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)
});
});
}
})
}