on
The Power of Frameworks
With Item Availability now a PWA, the next step is to make the data persistent.
One of the benefits of using frameworks like Angular is the availability of solutions for common programming tasks. This is often refereed to as patterns or how-to-guide
in plain terms. There is no need to design the app with all potential extensions in mind – the framework designers have done all that hard work for us. We only need to follow the framework’s best practice.
Because the app uses ngrx
for the app-state, the first solution-search is for a pattern that can save ngrx
store. And as often is the case, ngrx-store-localstorage
does exactly that.
By following the instruction, we only need to install the package.
$ npm i ngrx-store-localstorage --save
Add few lines to the /store/reducers.ts
file.
export const reducer: ActionReducerMap<IState> = { app: appReducer, e1: e1Reducer };
export function localStorageSyncReducer(reducer: ActionReducer<any>): ActionReducer<any> {
return localStorageSync({ keys: ['app'], rehydrate: true })(reducer);
}
export const metaReducers: Array<MetaReducer<any, any>> = [localStorageSyncReducer];
And make a small change to the initialisation of the StoreModule
in app.module.ts
.
imports: [
BrowserModule,
BrowserAnimationsModule,
AppRoutingModule,
FormsModule,
ServiceWorkerModule.register('/ngsw-worker.js', { enabled: environment.production }),
MaterialModule,
E1ServiceModule,
StoreModule.forRoot(reducer, { metaReducers }),
EffectsModule.forRoot([E1EffectsService]),
!environment.production ? StoreDevtoolsModule.instrument() : []
],
And that’s it!
The app
state is now automatically saved in the browser’s local storage every time it changes, as can be seen in Chrome’s Developer Tools.
One additional change is needed to make this more robust, and that is to change the key
from the rather generic app
to something more unique. The data in browser’s local storage is user secured – not app secured. A web app running under the same user’s credentials could therefore accidentally override it.