painless-redux-persist v2.0.1
Synchronize Redux state with localStorage or sessionStorage
Subscribe the Redux Store and replicate to localStorage
or sessionStorage
. The user could refresh page and keep the redux state.
Store config
Import the default method (you can call storePersist as the example below) from 'painless-redux-persist'
and pass store as parameter
import { createStore, combineReducers } from 'redux';
import storePersist from 'painless-redux-persist';
const combineReducer = combineReducers({
Category,
Post
});
export const store = createStore(combineReducer);
storePersist(store); // the default config synchronizes the entire store
sessionStorage
The default browser storage is localStorage
( which persists until the browser is closed), but you can change the default to sessionStorage
(persists until the tab is closed).
Just import it as the example below.
import storePersist from 'painless-redux-persist/session';
Blacklist
If you need to ignore some reducer, you can use the blacklist configuration.
The blacklist allows an array of strings (reducers keys).
storePersist(store, {
blacklist: ['Category']
});
Whitelist
If you want to sync just specific reducers, you can use the whitelist configuration.
The whitelist allows an array of strings (reducers keys).
storePersist(store, {
whitelist: ['Post']
});
Reducer example
To populate the initalState from browser storage, import defineState method from 'painless-redux-persist'
, pass your initialState
as first parameter and the reducer key as the second. (note that it's using currying)
import { defineState } from 'painless-redux-persist';
const defaultState = {
data: null
};
const initialState = defineState(defaultState)('Post');
export default (state = initialState, action) => {
switch (action.type) {
case 'ACTION1':
return {
...state,
data: action.payload
};
case 'ACTION2':
return {
...state,
data: null
};
default:
return state;
}
};
If you are using sessionStorage configuration, you will need to import the default state method as example below.
import { defineState } from 'painless-redux-persist/session';
Encrypt local state
In some situations you may want to encrypt the local state information. For that, you can pass your encrypt and decrypt methods.
const encryptMethod = btoa(state);
const decryptMethod = atob(state);
storePersist(store, {
encrypt: encryptMethod,
decrypt: decryptMethod,
});
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 'painless-redux-persist';
const state = getState();
If you need to reset the local store
import { resetState } from 'painless-redux-persist';
resetState();