Reputation: 6327
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
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
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