redux-storage
![npm version](https://img.shields.io/npm/v/redux-storage.svg?style=flat-square)
Installation
npm install --save redux-storage
Usage
import storage from 'redux-storage'
import createEngine from 'redux-storage/engines/reactNativeAsyncStorage';
import { createStore, applyMiddleware } from 'redux';
import * as reducers from './reducers';
const reducer = storage.reducer(combineReducers(reducers));
let engine = createEngine('my-save-key');
const middleware = storage.createMiddleware(engine);
const store = applyMiddleware(middleware)(createStore)(reducer);
const load = storage.createLoader(engine);
load(store);
Details
Engines
redux-storage/engines/reactNativeAsyncStorage
This will use AsyncStorage
out of react-native
.
redux-storage/engines/localStorage
Stores everything inside window.localStorage
. Warning! localStorage
does
not expose a async API and every save/load operation will block the JS thread!
Actions
import { LOAD, SAVE } from 'redux-storage';
function storeageAwareReducer(state = { loaded: false }, action) {
switch (action.type) {
case LOAD:
return { ...state, loaded: true };
case SAVE:
console.log('Something has changed and written to disk!');
default:
return state;
}
}
Middleware
If you pass an array of action types as second argument to createMiddleware
,
those will be added to a internal blacklist and wont trigger calls to
engien.save
.
import storage from 'redux-storage'
import { APP_START } from './constants';
const middleware = storage.createMiddleware(engine, [ APP_START ]);
Decorators
Filter
Use this decorator to write only part of your state tree to disk.
import storage from 'redux-storage'
engine = storage.decorators.filter(engine, [
['some', 'key'],
['another', 'very', 'nested', 'key']
]);
Debounce
This decorator will delay the expensive save operation for the given ms. Every
new change to the state tree will reset the timeout!
import storage from 'redux-storage'
engine = storage.decorators.debounce(engine, 1500);
Immutable
Convert parts of the state tree into ImmutableJS
objects on engine.load
.
import storage from 'redux-storage'
engine = storage.decorators.immutablejs(engine, [
['immutablejs-reducer'],
['plain-object-reducer', 'with-immutablejs-key']
]);
Todo
- Write tests for everything!