Redux Localstore Save

Synchronize Redux Store with localStorage

Project README

Synchronize Redux Store with localStorage/sessionStorage

npm version npm downloads Standard - JavaScript Style Guide

Subscribe Redux Store and replicate to localStorage, so user will can refresh page and keep the App state

Store example

Just import the default method (you can call storeSynchronize as the example above) from 'redux-localstore' and pass store as parameter

import { createStore, combineReducers } from 'redux';
import storeSynchronize from 'redux-localstore';

const combineReducer = combineReducers({
  Auth,
  Product
});

export const store = createStore(combineReducer);

storeSynchronize(store); // the default config synchronizes the whole store

localStorage / sessionStorage

The default browser storage is the localStorage (persists until the browser is closed), but since version 0.3.0 you can change the default to sessionStorage (persists until the tab is closed).

storeSynchronize(store, {
  storage: 'sessionStorage'
});

Blacklist

If you need to ignore some reducer, you can use the blacklist configuration:

storeSynchronize(store, {
  blacklist: ['Auth']
});

Whitelist

If you want to sync just specific reducers, you can use the whitelist configuration:

storeSynchronize(store, {
  whitelist: ['Product']
});

Reducer example

To populate the initalState from browser storage, import defineState method from 'redux-localstore', pass your defaultState as first parameter and the reducer key as second. (note that it's using currying)

import { defineState } from 'redux-localstore';

const defaultState = {
  data: null
};

const initialState = defineState(defaultState)('Product');

export default (state = initialState, action) => {
  switch (action.type) {
    case 'ACTION1':
      return {
        ...state,
        data: action.payload
      };
    case 'ACTION2':
      return {
        ...state,
        data: null
      };
    default:
      return state;
  }
};

Getting local state

This method gets the persisted state. It shouldn't be actually necessary, since the state from your redux store is supposed to be the same.

import { getState } from 'redux-localstore';

const state = getState();

If you need to reset the local store

import { resetState } from 'redux-localstore';

resetState();
Open Source Agenda is not affiliated with "Redux Localstore" Project. README Source: arojunior/redux-localstore
Stars
40
Open Issues
12
Last Commit
1 year ago
License
MIT

Open Source Agenda Badge

Open Source Agenda Rating