Last active
May 10, 2021 20:53
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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)); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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