Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MobX - Reset all store observables back to initial state?

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.

like image 744
Wonka Avatar asked Sep 04 '16 02:09

Wonka


2 Answers

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;
like image 176
Itamar Avatar answered Sep 17 '22 11:09

Itamar


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);
  }
}
like image 23
Sava Vidakovic Avatar answered Sep 18 '22 11:09

Sava Vidakovic