Flush state with an NgRx meta-reducer

Tim Deschryver
Tim Deschryver
timdeschryver.dev

Flush state with an NgRx meta-reducer

Use case

You want to (partially) flush the state.

Solution

Use a meta-reducer to listen to an action and flush the state by invoking the reducer with the undefined state so the reducers re-use their initial state.

/**
* Reset the whole state when the RESET action is dispatched
*/
function flush(reducer) {
return function (state: AppState | undefined, action: Action) {
if (action.type === 'RESET') {
return reducer(undefined, action);
}
return reducer(state, action);
};
}
/**
* Reset a partial state when the RESET action is dispatched,
* except for the authentication and design states
*/
function flush(reducer) {
return function (state: AppState | undefined, action: Action) {
if (action.type === 'RESET') {
return reducer(
{
authentication: state.authentication,
design: state.design,
},
action,
);
}
return reducer(state, action);
};
}

Feel free to update this blog post on GitHub, thanks in advance!

Enjoying the blog?

Support my work

If you enjoyed this post and found it useful, consider supporting my work. It helps me keep creating and sharing content like this. Thank you!