Search code examples
angularlocal-storagesession-storagengxs

NGXS storage-plugin change between local & session storage


I'm using NGXS with the @ngxs/storage-plugin. When I import the plugin inside my module I can config the plugin to use localStorage or sessionStorage via the storage option.

My App should use localStorage when the user checks the "remember me" option when logging in and use sessionStorage when he wont use the "remember me" option.

Any ideas how I can implement this with the @ngxs/storage-plugin?

@NgModule({
    imports: [
        CommonModule,
        NgxsModule.forRoot(STATES_MODULES, OPTIONS_CONFIG),
        NgxsStoragePluginModule.forRoot({storage: '????'}),
        NgxsReduxDevtoolsPluginModule.forRoot(DEVTOOLS_REDUX_CONFIG),
        NgxsLoggerPluginModule.forRoot(LOGGER_CONFIG)
    ],
    exports: [NgxsModule]
})
export class NgxsStoreModule {}


Solution

  • I would use a custom storage engine: https://www.ngxs.io/plugins/storage#custom-storage-engine

    If you can control your storage engine then that might work. Not sure if you can use angular's DI to inject the store/something else to figure out if the user is trying to set 'rememberMe' or not.

    export class MyStorageEngine implements StorageEngine {
      ....
    
      setItem(key: string, val: any): void {
        if (rememberMe) {
          // set with localStorage
        } else {
          // set with sessionStorage
        }
      }
      ....
    }