Subscribe Redux Store and replicate to localStorage
, so user will can refresh page and keep the App state
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
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'
});
If you need to ignore some reducer, you can use the blacklist configuration:
storeSynchronize(store, {
blacklist: ['Auth']
});
If you want to sync just specific reducers, you can use the whitelist configuration:
storeSynchronize(store, {
whitelist: ['Product']
});
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;
}
};
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();
import { resetState } from 'redux-localstore';
resetState();