Search code examples
arraysreactjsmobxcomputed-properties

Mobx, filter and unshift an array in @computed


Given an observable array holding an id-name-propertyName collection I'm trying to filter out a country array which has to be bound to a html select control in a React component. I need to present an empty default in my select html element. The filter for 'Country' works great, however when adding the .unshift(empty) portion I'm running into problems.

My observable:

class ReferenceStore {
  @observable referenceData=[];

My @computed so far:

  @computed get countries() {
    var empty = { id: 0, name: '' };
    var test = this.referenceData.filter(x => x.propertyName === "Country").unshift(empty);
    return test; 
  }

The problem is that this code results in the following error message in my component :

ReferenceStore__.a.countries.map is not a function 

How should I go about this? Thank you!


Solution

  • unshift returns the new length of the array, and not the array itself.

    You can do unshift first, and then return the array instead.

    @computed get countries() {
      var empty = { id: 0, name: '' };
      var test = this.referenceData.filter(x => x.propertyName === "Country");
    
      test.unshift(empty);
    
      return test; 
    }