Meta Reducers
A meta reducer is a higher order reducer that allows you to take action on the global state rather than a state slice. In NGXS, we don't have this concept but you can accomplish this with plugins.
An example of a meta reducer might be to clear the entire state when a user logs out. An example implementation would be:
1
import { getActionTypeFromInstance } from '@ngxs/store';
2
3
export function logoutPlugin(state, action, next) {
4
// Use the get action type helper to determine the type
5
if (getActionTypeFromInstance(action) === Logout.type) {
6
// if we are a logout type, lets erase all the state
7
state = {};
8
}
9
10
// return the next function with the empty state
11
return next(state, action);
12
}
Copied!
Then we import that like:
1
import { NgModule } from '@angular/core';
2
import { NGXS_PLUGINS } from '@ngxs/store';
3
4
@NgModule({
5
imports: [NgxsModule.forRoot([])],
6
providers: [
7
{
8
provide: NGXS_PLUGINS,
9
useValue: logoutPlugin,
10
multi: true
11
}
12
]
13
})
14
export class AppModule {}
Copied!
Now when we dispatch the logout action it will use our new plugin and erase the state.
Last modified 1yr ago
Copy link