NgRx and localStorage in combination

Viewed 6679

I'm kind of new to the concept of NGRX and state management as I came from back-end development and whenever i see and heard the term state management one thing comes in my mind is CQRS.

Well, some of the articles in the internet says that it is patterned from that. My Question is.. in my angular App.

Can i do something like, fetch data from the back-end then save to local storage if not exists? so every get request will look on the local storage and every save,update delete goes directly to a REST API then update the local storage if successful result form back-end?

I've been looking around for some examples about this but i am very unfortunate on that.

Also, reason why local storage is because I'm thinking PWA as well

1 Answers

NGRX allows you to create a middleware Document.

Developers can think of meta-reducers as hooks into the action->reducer pipeline. Meta-reducers allow developers to pre-process actions before normal reducers are invoked.

import merge from 'lodash.merge';
import { StoreModule, ActionReducer, MetaReducer } from '@ngrx/store';
import { reducers } from './reducers';
 
export function storageMetaReducer<S, A extends Action = Action>(reducer: ActionReducer<S, A>) {
      return function(state: S, action: A): S {
        const nextState = reducer(state, action);
        const savedState = JSON.parse(localStorage.getItem('__storage__')) || {};
        merge(nextState, savedState);
        localStorage.setItem('__storage__', nextState)
        return nextState;
      };
    }
    
export const metaReducers: MetaReducer<any>[] = [storageMetaReducer];

@NgModule({
  imports: [
    StoreModule.forRoot(reducers, { metaReducers })
  ],
})

Main difference between localStorage vs sessionStorage

localStorage is persistent between tabs and sessionStorage is per tab.

Related