9

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?

typos
  • 5,932
  • 13
  • 40
  • 52

3 Answers3

14

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

var that = this;

and then reference that.setState.

ktilcu
  • 3,032
  • 1
  • 17
  • 15
8

This has because you have a different scope inside the function. When using a function it has it's own scope. And "this" used out side the function is not the same when you use it inside the function. The best way of doing this is having a variable "that" and assign the previous "this" to "that".

class Hello extends React.Component {
    constructor(props) {
        super(props);
        this.getAttachment = this.getAttachment.bind(this);
        this.state = {attachmenet: ""};
    }

    getAttachment(url) {

         //Code you need to add
         var that = this;

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

            var response = responseText.json();

            response.then(function(response){
               //code you need to change
               that.setState({ attachment: response });
            });
         });
     }

     render() {
         this.getAttachment();
         return <div dangerouslySetInnerHTML={{__html:this.state.attachment}}>
       </div>;
     }


}
Shashith Darshana
  • 2,715
  • 1
  • 25
  • 27
1

try changing the getAttachment function to getAttachment = (url) => {...} and delete .bind(this)

Sean Wu
  • 31
  • 2