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.
Why not going with the following approach
class MyQuestionStore {
   @observable asked;
   @observable answered;
   @observable question;
   constructor() {
      super()
      this.init()
   }
   @action reset() {
      this.init()
   }
   @action init() {
     this.asked = 'today';
     this.answered = false;
     this.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;
To reset store you can do something like this:
const initialValue = {
  name: 'John Doe',
  age: 19,
}
@action reset() {
  Object.keys(initialState).forEach(key => this[key] = initialState[key]);
}
And you can set initial store values:
class myStore {
  constructor() {
    extendObservable(this, initialState);
  }
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With