Cannot read property 'setState' of undefined when using fetch [duplicate]

447
March 19, 2017, at 09:30 AM

This question already has an answer here:

  • How does the “this” keyword work? 17 answers
  • Arrow function vs function declaration / expressions: Are they equivalent / exchangeable? 2 answers

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?

Rent Charter Buses Company
READ ALSO
Template Literals from external file

Template Literals from external file

I'd like to pass some variables into an html file I have and then send them via emailMost of that isn't very relevant to the issue so I'm going to go with a basic example

453
How to calculate bounding box of text object on dynamic canvas

How to calculate bounding box of text object on dynamic canvas

I am attempting to calculate the pixel height and width of a text object on a html canvasI've already attempted some code seen below but I've been getting wrong results

707
Making Materialize CSS Tooltips stay when hovering over them

Making Materialize CSS Tooltips stay when hovering over them

A piece I'm currently working on is calling for tooltips that display when you hover over part of an SVG element, disappear as normal on mouse-out but providing the mouse does not go over the tooltip itselfWe are using Materialize CSS which does come with a tooltip...

412
how to stop ng-repeat in the middle of the repeat in angular js

how to stop ng-repeat in the middle of the repeat in angular js

I'm trying to build a tic tac toe game and am having issues with the stylingI have a ng-repeat for all 9 squares and need to add a div after every 3rd square so that the next row can be built

385