2

How to preserve the state after browser tab is refreshed in NGXS? Ngrx version of the question is asked here?

dasfdsa
  • 7,102
  • 8
  • 51
  • 93

2 Answers2

5

You can preserve state using the storage plugin:

https://ngxs.gitbook.io/ngxs/plugins/storage

Rich Duncan
  • 1,845
  • 1
  • 12
  • 13
2

Revamping my entire answer. Found a better way to persist data: through meta-reducers

persist.plugin.ts

import {getActionTypeFromInstance} from '@ngxs/store';
import {ConstantsService} from '../constants.service';
import {tap} from 'rxjs/operators';

/*
* This plugin will
* 1. Store the state in localstorage, after every action
* 2. After page is refresed, read from localstorage data and write that into state
* */
export function persistPlugin(state, action, next) {

  console.log('entering plugin=================');
  // After every refresh first action fired will be @@INIT
  if (getActionTypeFromInstance(action) === '@@INIT') {

    // reading from local storage and writing into state, when app is refreshed
    let storedStateStr = localStorage.getItem('LOCALSTORAGE_APP_STATE');
    let storedState = JSON.parse(storedStateStr);
    state = {...state, ...storedState};
    return next(state, action);
  }
  
  return next(state, action).pipe(tap(result => {
  //following code will trigger after reducer
    console.log('Action happened!', result);
    localStorage.setItem('LOCALSTORAGE_APP_STATE', JSON.stringify(result));;
  }));
}

app.module.ts

  providers: [...,{
    provide: NGXS_PLUGINS,
    useValue: persistPlugin,
    multi: true
  }],
ewdegraaff
  • 13
  • 3
dasfdsa
  • 7,102
  • 8
  • 51
  • 93