Vuex-module-decorators: Reset store

Created on 11 Jun 2020  路  8Comments  路  Source: championswimmer/vuex-module-decorators

How can I reset vuex store to initial state? normally without VuexModule I can reset store easily like this:

// default state
const getDefaultState = () => ({
    name: 'example',
    age: 20
})

// store
const store = new Vuex.Store({
    state: getDefaultState(),
    mutations: {
        resetState(state) {
            Object.assign(state, getDefaultState())
        }
    }
})

But I can't figure out how could I achieve this with vuex-module-decorators

Most helpful comment

Hey @delowardev did you managed to fix this?

@bangjelkoski Yes, very simple solution:

const defaultState = {
   firstName: "John",
   lastName: "Doe"
};

@Module({ name: "example", namespaced: true })
export default class ExampleModule extends VuexModule {
   firstName = defaultState.firstName;
   lastName = defaultState.lastName;

  @Mutation
  resetState() {
       this.firstName = defaultState.firstName;
       this.lastName = defaultState.lastName;
  }
}

All 8 comments

Hey @delowardev did you managed to fix this?

Hey @delowardev did you managed to fix this?

@bangjelkoski Yes, very simple solution:

const defaultState = {
   firstName: "John",
   lastName: "Doe"
};

@Module({ name: "example", namespaced: true })
export default class ExampleModule extends VuexModule {
   firstName = defaultState.firstName;
   lastName = defaultState.lastName;

  @Mutation
  resetState() {
       this.firstName = defaultState.firstName;
       this.lastName = defaultState.lastName;
  }
}

Makes sense, thank you!

If there are many state in module, assign value one by one would be a disaster.

@bill-lee-aics if there are many states, a loop could be helpful. for example:

@Mutation
resetState() {
  Object.keys(defaultState).forEach(key => {
      this[key] = defaultState[key];
  })
}

Thanks for quick reply! But how to declare class initial state from a defaultState?
Supposing it can be done in this way:

constructor(){
  super();
  Object.keys(defaultState).forEach(key => {
      this[key] = defaultState[key];
  })
}

or

@Moudle({ state: () => defaultState })

But neither of them is working.

@bill-lee-aics how about this one?

constructor(){
  super();
  Object.assign(this, defaultState);
}

@delowardev
Still not work. Also, it would lead to property not exist on type error.
I think this issue can't be easily resolved.
It's a defect in design of this package.
Thanks for your help!

Was this page helpful?
0 / 5 - 0 ratings