Applying transform filters with redux-persist

Jignesh Kakadiya
2 min readJan 16, 2018

--

While working on one of the react-native application I stumbled upon the need of filtering app redux state upon rehydration.

Why?
Some of the redux state is not persisted or hydrated between app loads. The primary use of transforms is to clear the navigation state between app loads, because otherwise the user can sometimes get into a invalid state which they can’t clear by closing the app — either they have to uninstall and reinstall the app to get it working.

In simple words redux persists keeps your data until storage is cleared. That means if user has closed and then opened the app. App state will still persist in the store.

How to do it?
1. blacklist
blacklisted keys will get cleared when app is closed/stopped.
Navigation: react-navigation have their own state which gets stored using redux-persist and when we open the app after closing it. We end up in the last visited route. If we want user (loggedin) to go the home rather than any other page we need to black list `key` for navigation reducer.

2. Whitelist
Whitelisted keys won’t get cleared when app is closed/stopped.
Use case: When logged in user visits the app after closing it once. We would like to show them home screen instead of splash screen. So we black list all other keys except user token.

import { createWhitelistFilter } from 'redux-persist-transform-filter';import reducer1 from './reducer1';
import reducer2 from './reducer2';
import session from './session'; //reducer
import nav from './nav'; // reducer
const config = {
key: 'MyApp',
storage,
blacklist: ['nav', 'reducerKey1', 'reducerKey2'],
transforms: [
createWhitelistFilter('session', ['token', 'user']),
createTransform(
state => state,
state =>
Object.assign({}, state, {
session: {...state.session, timestamp: Date.now() },
}),
{
whitelist: 'session',
}
),
],
};
const reducers = {
reducerKey1: reducer1,
reducerKey2: reducer2,
nav: nav,
session: session
}
const appReducer = persistCombineReducers(config, reducers);

The above snippet will clear blacklisted key states.
createWhitelistFilter is used to whitelist specific keys from the session state.

--

--