0

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

            });
        }
    })
}
5
  • normally people dont call the API directly inside the componentdidMount. also try using arrow function for callbacks Commented Feb 27, 2020 at 5:47
  • 2
    @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? Commented Feb 27, 2020 at 6:11
  • @bravemaster its fine, but normally you don't put API calls directly in the component as it cant be reused Commented Feb 27, 2020 at 6:18
  • 2
    @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? Commented Feb 27, 2020 at 6:21
  • @Sujit.Warrier how would you suggest I improve upon the way and place I'm using fetch? Commented Feb 27, 2020 at 6:59

1 Answer 1

2

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

            });
        }
    })
Sign up to request clarification or add additional context in comments.

8 Comments

How would you suggest I use this siteData variable in the render function?
once you setState siteData you will be able to access it from anywhere inside the component by this.state.siteData
When I try to .map the variable, I get an error saying it's not a function. :/
'.map' works only on Array. May be you are trying to map an array before it is available, please remember both fetch and setState are asynchronous
here is one of my sample snippet for working with fetch api in react: codepen.io/mostafiz93/pen/KKpmPjM You can set initial state to avoid undefined state data.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.