Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

setState inside Promise in React

I have a function in my React code defined like this:

getAttachment(url) {
    fetch(url).then((responseText) => {

        var response = responseText.json();

        response.then(function(response){
            this.setState({ attachment: response });
        });
    }.bind(this));
}

But I get an error when this compiles, saying that I have an unexpected token at the .bind(this). Any ideas, how to set state inside a promise?

like image 589
typos Avatar asked Nov 06 '17 02:11

typos


1 Answers

Instead of binding this you could just scope the reference to this. like

var that = this;

and then reference that.setState.

like image 82
ktilcu Avatar answered Sep 30 '22 15:09

ktilcu