Store: [Feature] Reset state to default

Created on 13 Jul 2018  路  5Comments  路  Source: ngxs/store

Feature Request - reset a state to default

I've found that in a few scenarios (log out, switch account etc) it'd be useful to be able to easily reset a state to its default values.

So for a state like this:

export interface MyStateModel {
    name: string;
    rating: number;
}

@State<MyStateModel>(
{   
   name: 'myState',
   defaults: {
       name: '',
       rating: 1
  }
})
export class MyState { .. }

I could write something like:

@Action(LogOutComplete)
onLogOut({reset}: StateContext<MyStateModel>) {
    reset();
}

Currently, I'm writing like this, duplicating my defaults definition.

@Action(LogOutComplete)
onLogOut({setState}: StateContext<MyStateModel>) {
    setState({
      name: '',
      rating: 1
   });
}

This is distinct from the store.reset function that was recently added.

Most helpful comment

hey @amcdnl and @eranshmil
Thanks for your answers. I went through #501. If I understood correctly, are you suggesting that we should write state resetters (to default) for each substate?
I currently have 5 substates in my project, do I need to write reset action for all of these 5 states? That will be a bit tedious imho. Sorry if I misunderstood anything.
Thanks.

All 5 comments

You can change all properties to optional in the model and then use setState({}) or use a const for the defaults, just like in my example in the pr #501.

Ya, I agree. That is the appropriate way to handle this.

@eranshmil that's great, thanks for the tip! The const for defaults would suit us, I'll refactor it that way 馃憤

hey @amcdnl and @eranshmil
Thanks for your answers. I went through #501. If I understood correctly, are you suggesting that we should write state resetters (to default) for each substate?
I currently have 5 substates in my project, do I need to write reset action for all of these 5 states? That will be a bit tedious imho. Sorry if I misunderstood anything.
Thanks.

If you want to clear the whole store state, you can use meta reducers.
https://ngxs.gitbook.io/ngxs/advanced/meta-reducer

The defaults way used only to clear a specific state.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

piernik picture piernik  路  5Comments

ToxicToast picture ToxicToast  路  6Comments

kyusupov33 picture kyusupov33  路  3Comments

goodmite picture goodmite  路  5Comments

rweng picture rweng  路  5Comments