Skip to content

How to create async storage with NGXS #156

@SteveLemire

Description

@SteveLemire

I was able to manage our own storage service that provides functionality to support async storage with the help of StorageMap library that use IndexedDb and AsyncStorageEngine.

  1. Install StorageMap .

  2. Install AsyncStorageEngine

  3. Create a new storage service and implement AsyncStorageEngine with missing members like this:

export class StorageService implements AsyncStorageEngine {
  constructor(private storageMap: StorageMap}
  1. In your app.module.ts, configure your NgxsModule and other packages like this:
    NgxsModule.forRoot(
      [
        // Add your state classes here
      ],
      {
        developmentMode: !environment.production,
        selectorOptions: {
          // https://www.ngxs.io/concepts/select#selector-options
          // These Selector Settings are recommended in preparation for NGXS v4
          suppressErrors: false,
          injectContainerState: false,
        },
      },
    ),
    // https://github.com/ngxs-labs/async-storage-plugin
    NgxsAsyncStoragePluginModule.forRoot(StorageService),
   // https://github.com/ngxs-labs/async-storage-plugin
    NgxsDataPluginModule.forRoot([NGXS_DATA_STORAGE_PLUGIN]),
  1. In your state class, add the following decorators:
@Persistence({
  useClass: StorageService,
})
@StateRepository()
@State<MyStateModel>({...

Et voilà!
You can now use your async StorageService with NGXS!

Note: This will not work with IE11 and target type ES5 because ngxs-lab/data @persistence decorator use the Package class that is only available with ES6 (ES2015). I was not able get this work event if I tried with the following packages:

Originally posted by @SteveLemire in ngxs-labs/data#299 (comment)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions