st_clair_clarke
st_clair_clarke

Reputation: 5705

Resetting state in ngxs

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

Upvotes: 5

Views: 13112

Answers (4)

Ramin Ar
Ramin Ar

Reputation: 1331

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());
}

Upvotes: 1

mehmetakifalp
mehmetakifalp

Reputation: 455

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

It's an ngxs plugin, easy to implement.

Upvotes: 5

Garth Mason
Garth Mason

Reputation: 8001

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

Upvotes: 3

Ihor Klymenok
Ihor Klymenok

Reputation: 9

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.

Upvotes: 0

Related Questions