Skip to content

Instantly share code, notes, and snippets.

@btroncone
Last active May 10, 2021 20:53
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save btroncone/d3095cf56f63a9e948a1 to your computer and use it in GitHub Desktop.
Save btroncone/d3095cf56f63a9e948a1 to your computer and use it in GitHub Desktop.
Basic demonstration of how NgRx middleware can be used to keep local storage in sync with user-defined state slices.
//specify what state slices you would like to keep synced with local storage
export function main() {
return bootstrap(TodoApp, [
provideStore(APP_REDUCERS),
localStorageMiddleware('todos', 'visibilityFilter')
])
.catch(err => console.error(err));
}
import {provide} from 'angular2/core';
import {Observable} from 'rxjs/Observable';
import {POST_MIDDLEWARE} from '@ngrx/store';
const validateStateKeys = (keys: string[]) => {
return keys.map(key => {
if(typeof(key) !== 'string'){
throw new TypeError(
`localStorageMiddleware Unknown Parameter Type: `
+ `Expected type of string, got ${typeof key}`
);
}
return key;
});
};
const createLocalStorageMiddleware = (keys : string[]) => {
const stateKeys : string[] = validateStateKeys(keys);
return (obs:Observable<any>) => {
return obs.do(state => {
stateKeys.forEach(key => {
let stateSlice = state[key];
if (typeof(stateSlice) !== 'undefined') {
localStorage.setItem(key, JSON.stringify(state[key]));
}
});
});
}
};
export const localStorageMiddleware = (...keys : string[]) => {
const middleware = createLocalStorageMiddleware(keys);
return provide(POST_MIDDLEWARE, {
multi: true,
useValue: middleware
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment