0

I searched StackOverflow for this issue on StackOverflow, but haven't found an answer to this yet, so bear with me if it has already been answered.

I'm defining a class in ES6 (using ReactJS, although this is somewhat irrelevant to the question) as follows. I would like to modify this.size and this._cache from my fetch callback, however it seems I cannot directly manipulate "this" since it refers to another object than the class instantiation, obviously. When defining var that to be bound to this, it does work in referring to the object, but I feel this isn't the ES6 best way to do this:

class MyDataListStore {

    constructor(url) {
        this.url = url;
        this.size = 0;
        this._cache = [];
        this.getRemoteData();
    }

    getRemoteData() {
        var that = this;
        fetch(this.url).then(function(response) {
             return response.json();
        }).then(function(j) {
             that.size = j["total"];
             that._cache = j["table"];
    });
    }
}

I feel like I'm missing something with ES6, that there may be a better way to do this.

Thanks!

Loic Duros
  • 5,472
  • 10
  • 43
  • 56

1 Answers1

0

This should do it:

getRemoteData() {
  fetch(this.url)
  .then((response) => response.json())
  .then((j) => {
     this.size = j.total;
     this._cache = j.table;
  });
}
Samuli Hakoniemi
  • 18,740
  • 1
  • 61
  • 74
  • What in this makes a difference in regards to scope? In my initial example "this" was bound to the callback, but in this one it is bound to the class object? – Loic Duros Mar 01 '16 at 14:36
  • @Loic Duros https://github.com/lukehoban/es6features#arrows - Read this first – John Mar 01 '16 at 14:49