0

As in the title, I'm confused about the behavior of fetch calling the setState method in a React component.

This way it works:

    fetch(url)
        .then((response) => {
            return response.json()
        })
        .then((json) => {
            this.setState({page: json});
        });

This way it fails:

    fetch(url)
        .then(function (response) {
            return response.json()
        }).then(function (json) {
            console.log('parsed json', json);

            this.setState({page: json}); // Cannot read property 'setState' of undefined

        }).catch(function (ex) {
            console.log('parsing failed', ex)
        });

What's the reason of such behavior?

Felix Kling
  • 705,106
  • 160
  • 1,004
  • 1,072
asliwinski
  • 1,488
  • 3
  • 17
  • 31
  • 1
    you can not refer to the instance using this in the function block when defined like that. this does not the component you want to because the scope changes in function definition. – benchpresser Mar 19 '17 at 00:24
  • 3
    This has nothing to do with React. Read up on the difference between arrow functions and "normal" functions. – Felix Kling Mar 19 '17 at 00:32
  • 2
    Normally, 'this' changes inside of a function, depending on how its called. However, "fat arrow functions" (=>) have what's called "lexical this" which basically means that it can't change. – Nathan Friedly Mar 19 '17 at 00:53
  • All clear now, thanks! – asliwinski Mar 19 '17 at 03:09

0 Answers0