Search code examples
javascriptnode.jsfetches6-promisemobx

How to rewrite this promise chain to avoid need of multiple functions?


I'm just starting with mobx and react (which is a great team, btw.!) and I have a little problem with my store. I want to asynchronously fetch some data from an existing API and then use this data to update some existing observables in my store:

class StationStore {

  @observable stations = []

  loadStations() {
    fetch('http://localhost:3000/api/station/getStations')
    .then(function(response) { return response.json() })
    .then(stations=>this.parseStations(stations));
  }

  @action parseStations(stations) {
    var newStations = stations.map((station)=>{
      let s = new Station;
      s.id=station.id;
      s.name=station.Text;
      s.deviceType=station.DeviceType;
      return s;
    });
    this.stations.replace(newStations);
  }
}

As you can see, I need to divide my logic into two separate functions in order to be able to access this.stations. I tried to include the map and replace part into the loadStations()'s second then(), but when I do so, I cannot access my store because this is undefined in there.

How can I fix this?


Solution

  • Use var self = this; should solve your problem

    class StationStore {
        @observable stations = [];
    
        loadStations() {
            var self = this;
            fetch('http://localhost:3000/api/station/getStations')
                .then(function (response) {
                    return response.json()
                })
                .then(stations => {
                    self.stations.replace(stations.map((station) => {
                        let s = new Station;
                        s.id = station.id;
                        s.name = station.Text;
                        s.deviceType = station.DeviceType;
                        return s;
                    }));
                });
        }
    }