MobX - Reset all store observables back to initial state?
I ended up having to repeat the default observables in the reset function, so it looks like this:
class MyQuestionStore {
@observable asked = 'today';
@observable answered = false;
@observable question = {
upvotes: 0,
body: null,
asker: null,
askerPoints: null,
askerBadges: null
}
@action reset = () => {
this.asked = 'today';
this.answered = false;
this.question = {
upvotes: 0,
body: null,
asker: null,
askerPoints: null,
askerBadges: null
}
}
}
const myQuestionStore = new MyQuestionStore();
export default myQuestionStore;
I still feel there is a better way than to repeat it and keep it DRY. I will keep the question open for now, hoping there is a better DRY answer.
EDIT: this is an old answer that doesn’t work in newer versions of mobx.
If you use the reset()
to initialize the object, you could avoid duplication of code. Here is what I mean:
import { extendObservable } from "mobx";
class MyQuestionStore {
constructor() {
this.reset();
}
@action reset() {
extendObservable(this, {
asked: 'today',
answered: false,
question: {
upvotes: 0,
body: null,
asker: null,
askerPoints: null,
askerBadges: null
}
});
}
}
If you don't need to reset deeply, the createViewModel
utility from mobx-utils
might come in handy: https://github.com/mobxjs/mobx-utils/#createviewmodel