Ryan
Ryan

Reputation: 6327

Mobx update a single property in an object

I have created an observable property in my store as follows

class Store {
  @observable values = { id: '', name: '' }
}

This observable object is used in a form, how can I reset these values after the form is submitted?

Upvotes: 1

Views: 3133

Answers (2)

XPX-Gloom
XPX-Gloom

Reputation: 601

@Tholle's solution is good if you don't extend properties to the this.values observable. if you do, the reset() method will not clear newly extended properties.

Here's my solution to this:

class Store {
    const initValues = {id: '', name: ''};
    @observable values = {};
    @action resetValues() {
        Object.keys(this.values).forEach(key => delete this.values[key]);
        extendObservable(this.values, initValues);
    }
    constructor() {
        This.resetValues();
    }
}

or even better, to use observable map instead:

class Store {
    const initValues = {id: '', name: ''};
    @observable values = new Map();
    @action resetValues() {
        this.values.replace(initValues);
    }
    constructor() {
        this.resetValues()
    }
}

Upvotes: 0

Tholle
Tholle

Reputation: 112787

You could use extendObservable and implement a reset method on your class:

const initValues = { id: '', name: '' };

class Store {
  @observable values = {};
  constructor() {
    extendObservable(this.values, initValues);
  }

  reset() {
    extendObservable(this.values, initValues);
  }
}

Upvotes: 1

Related Questions