0
votes

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

            });
        }
    })
}
1
normally people dont call the API directly inside the componentdidMount. also try using arrow function for callbacksSujit.Warrier
@Sujit.Warrier I think it's OK to call APIs in componentDidMount. You can define service or other helper methods but I think they're generally called in componentDidMount. What do you suggest?glinda93
@bravemaster its fine, but normally you don't put API calls directly in the component as it cant be reusedSujit.Warrier
@Sujit.Warrier In React, everything is a component. And one must call Api in order to fetch data unless it uses static mockup data. And that method should be called in componentDidMount. After data is fetched, those will be passed to child components as props. So it's okay and common to call api in componentDidMount. But hard-coding urls like the above code is a bad practice. What do you think?glinda93
@Sujit.Warrier how would you suggest I improve upon the way and place I'm using fetch?sindhugauri

1 Answers

2
votes

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

            });
        }
    })