Home

Awesome

ngrx-store-localstorage

bundle size npm weekly downloads semantic-release CircleCI

Simple syncing between ngrx store and local or session storage.

Dependencies

ngrx-store-localstorage depends on @ngrx/store and Angular 12+.

Usage

npm install ngrx-store-localstorage --save
  1. Wrap localStorageSync in an exported function.
  2. Include in your meta-reducers array in StoreModule.forRoot.
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { StoreModule, ActionReducerMap, ActionReducer, MetaReducer } from '@ngrx/store';
import { localStorageSync } from 'ngrx-store-localstorage';
import { reducers } from './reducers';


const reducers: ActionReducerMap<IState> = {todos, visibilityFilter};

export function localStorageSyncReducer(reducer: ActionReducer<any>): ActionReducer<any> {
  return localStorageSync({keys: ['todos']})(reducer);
}
const metaReducers: Array<MetaReducer<any, any>> = [localStorageSyncReducer];

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

API

localStorageSync(config: LocalStorageConfig): Reducer

Provide state (reducer) keys to sync with local storage. Returns a meta-reducer.

Arguments

LocalStorageConfig

An interface defining the configuration attributes to bootstrap localStorageSync. The following are properties which compose LocalStorageConfig:

Usage

Key Prefix

localStorageSync({
  keys: ['todos', 'visibilityFilter'], 
  storageKeySerializer: (key) => `cool_${key}`, 
});

In above example Storage will use keys cool_todos and cool_visibilityFilter keys to store todos and visibilityFilter slices of state). The key itself is used by default - (key) => key.

Target Depth Configuration

localStorageSync({
  keys: [
      { feature1: [{ slice11: ['slice11_1'], slice14: ['slice14_2'] }] }, 
      { feature2: ['slice21'] }
  ],
});

In this example, feature1.slice11.slice11_1, feature1.slice14.slice14_2, and feature2.slice21 will be synced to localStorage.feature1 and localStorage.feature2.

Known Workarounds

  1. Sync state across multiple tabs

Release Notes / Changelog

From version 10 onwards, check GitHub Releases for release notes. For older versions check the CHANGELOG.md.

Contributing

See CONTRIBUTING.md for instructions on how to contribute.