Sunday, June 2, 2024
 Popular · Latest · Hot · Upcoming
188
rated 0 times [  195] [ 7]  / answers: 1 / hits: 17552  / 8 Years ago, sun, september 4, 2016, 12:00:00

Given a MyQuestionStore store:



class MyQuestionStore {
@observable asked = 'today';
@observable answered = false;
@observable question = {
upvotes: 0,
body: null,
asker: null,
askerPoints: null,
askerBadges: null
}
// some more initial state observables...
// some actions below...
}

const myQuestionStore = new MyQuestionStore();
export default myQuestionStore;


What would be the correct way to reset all store observables back to their initial states data ('today'/false/0/null/etc..)?



NOTE: Something like MyQuestionStore.reset() for example I think would be a good MobX way, but I don't think it exists. I would have to write an action called reset and manually reset each observable back to its initial state. I don't think that would be the right way, since if I add more observables, I would have to manually add them to the reset action every time.


More From » mobx

 Answers
48

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
}
});
}
}

[#60819] Thursday, September 1, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jennie

Total Points: 593
Total Questions: 102
Total Answers: 106

Location: Federated States of Micronesia
Member since Fri, Sep 16, 2022
2 Years ago
jennie questions
;