Is the ngrx store persistent?

2019-10-09 16:53发布

问题:

Is the ngrx store persistent? In other words can we close the browser reopen it, and retrieve state that was added to the ngrx store?

回答1:

Currently ngrx/store doesn't support such functionality. But you can maintain state by using a library like ngrx-store-persist to save data to the browsers indexedDB, localStorage or WebStorage. This library automatically saves and restores ngrx/store's data. You just need to add redux keys that you want to store in the config (see "Usage" section).



回答2:

You can maintain state by using a library like idb.js to save data to the browsers indexDB, then by using the ngrx effect you can have an init effect to reload the state back when webapp loads. here is a example code let say I want to reload selected language. the effect would be:

 @Effect()
  init$: Observable<Action> = defer(() => {
    return from(storageDb.readData('app', Lang.ActionType.LANG_KEY)).pipe(
      map((data: any) => {
        const tmpData = data ? data.state : {dir: 'rtl', selected: 'ar'};
        this.translate.setDefaultLang(tmpData.selected);
        return new Lang.LanguageInit(tmpData);
      })
    );
  });

the storageDb.readData is a wrapper for idb to load data by key, the effect will kick in when effects are getting loaded it will get the data from the indexdb and if it does not find any sets default value then dispatchs an Action. ngrx best practices is to use promises in effects not in reducers since loading the data is async operation, then in your state reducer you can catch the Action like so:

case lang.ActionType.LANGUAGE_INIT: {
      return {...state, ...action.payload};
}

Using it in this way you can slice your states save them and loaded them even when lazyloading.



回答3:

The nrxg/store is in memory only. To manage state via the browser with something like pouchdb ngrx/effects can be used. More here.