Resetting state in ngxs
Asked Answered
C

4

5

When I add some new data to my state, the new data does not appear in my log or DevTool Ui.

Is there a mechanism to reset the state so that the data will appear. It seems that the old data from some cache is still being shown.

Thanks

Celestial answered 8/6, 2018 at 3:42 Comment(1)
Please provide details (e..g sample code) to describe what you have done?Lunch
A
5

I prefer to use this reset plugin; https://github.com/ng-turkey/ngxs-reset-plugin

It's an ngxs plugin, easy to implement.

Alaster answered 19/2, 2019 at 7:13 Comment(0)
N
3

In v3.1 there is a reset function on the store that allows you to reset state see the docs here

Norland answered 6/7, 2018 at 7:47 Comment(0)
R
1

You can simply add an action to your app.state.ts file as follows

The Action to reset the state

@Action(ResetAppState)
resetState(ctx: StateContext<AppStateModel>): Observable<AppStateModel> {
   return of(ctx.getState()).pipe(
      map(currentState => {
         ctx.patchState({/* enter initial/reset values here */});
         return currentState;
      })
   );
}

You must also add the action into the app.action.ts file as

export class ResetAppState {
  static readonly type = '[AppState] Reset App State';
}

Now you can dispatch the action in your service or component easily to reset the NGXS state as follows:

constructor(private store: Store) {}

yourMethod(): void {
    this.store.dispatch(new ResetAppState());
}
Rehearse answered 18/8, 2021 at 9:35 Comment(0)
H
0

For state reset I try to use "meta-reducer" concept via plugin (https://ngxs.gitbook.io/ngxs/advanced/meta-reducers), but I have trouble with re-initialize state to default value for each slice.

Hofuf answered 26/6, 2018 at 5:37 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.