• This repository has been archived on 29/Nov/2018
  • Stars
    star
    675
  • Rank 66,879 (Top 2 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created over 9 years ago
  • Updated over 7 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Persistence layer for redux with flexible backends

redux-storage

build dependencies devDependencies

license npm version npm downloads Code Climate

Save and load the Redux state with ease.

Moved to the react-stack organisation

My focus has left the node / react ecosystem and this module has got a new home over at react-stack!

Features

  • Flexible storage engines
  • Flexible state merger functions
  • Storage engines can be async
  • Load and save actions that can be observed
    • SAVE: { type: 'REDUX_STORAGE_SAVE', payload: /* state tree */ }
    • LOAD: { type: 'REDUX_STORAGE_LOAD', payload: /* state tree */ }
  • Various engine decorators
  • Black- and whitelist actions from issuing a save operation

Installation

npm install --save redux-storage

And you need to install at least one redux-storage-engine, as redux-storage is only the "management core".

Usage

import * as storage from 'redux-storage'

// Import redux and all your reducers as usual
import { createStore, applyMiddleware, combineReducers } from 'redux';
import * as reducers from './reducers';

// We need to wrap the base reducer, as this is the place where the loaded
// state will be injected.
//
// Note: The reducer does nothing special! It just listens for the LOAD
//       action and merge in the provided state :)
// Note: A custom merger function can be passed as second argument
const reducer = storage.reducer(combineReducers(reducers));

// Now it's time to decide which storage engine should be used
//
// Note: The arguments to `createEngine` are different for every engine!
import createEngine from 'redux-storage-engine-localstorage';
const engine = createEngine('my-save-key');

// And with the engine we can create our middleware function. The middleware
// is responsible for calling `engine.save` with the current state afer
// every dispatched action.
//
// Note: You can provide a list of action types as second argument, those
//       actions will be filtered and WON'T trigger calls to `engine.save`!
const middleware = storage.createMiddleware(engine);

// As everything is prepared, we can go ahead and combine all parts as usual
const createStoreWithMiddleware = applyMiddleware(middleware)(createStore);
const store = createStoreWithMiddleware(reducer);

// At this stage the whole system is in place and every action will trigger
// a save operation.
//
// BUT (!) an existing old state HAS NOT been restored yet! It's up to you to
// decide when this should happen. Most of the times you can/should do this
// right after the store object has been created.

// To load the previous state we create a loader function with our prepared
// engine. The result is a function that can be used on any store object you
// have at hand :)
const load = storage.createLoader(engine);
load(store);

// Notice that our load function will return a promise that can also be used
// to respond to the restore event.
load(store)
    .then((newState) => console.log('Loaded state:', newState))
    .catch(() => console.log('Failed to load previous state'));

Details

Engines, Decorators & Mergers

They all are published as own packages on npm. But as a convention all engines share the keyword redux-storage-engine, decorators can be found with redux-storage-decorator and mergers with redux-storage-merger. So it's pretty trivial to find all the additions to redux-storage you need πŸ˜„

Actions

redux-storage will trigger actions after every load or save operation from the underlying engine.

You can use this, for example, to display a loading screen until the old state has been restored like this:

import { LOAD, SAVE } from 'redux-storage';

function storageAwareReducer(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 won't trigger calls to engine.save.

import { createMiddleware } from 'redux-storage'

import { APP_START } from './constants';

const middleware = createMiddleware(engine, [ APP_START ]);

If you want to whitelist all actions that are allowed to issue a engine.save, just specify them as third argument.

import { createMiddleware } from 'redux-storage'

import { SHOULD_SAVE } from './constants';

const middleware = createMiddleware(engine, [], [ SHOULD_SAVE ]);

License

The MIT License (MIT)

Copyright (c) 2015 Michael Contento

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

More Repositories

1

redux-log-slow-reducers

Warn about slow reducers used in your redux app
JavaScript
141
star
2

circleci-matrix

Small utility to mirror TravisCI's build matrix on CircleCI.
Shell
81
star
3

awsenv

Simple AWS environment manager (aka rbenv for aws)
Shell
55
star
4

redux-storage-engine-reactnativeasyncstorage

react-native/AsyncStorage based engine for redux-storage
Makefile
35
star
5

revolver

Pythonic server orchestrating based on fabric / cuisine
Python
27
star
6

redux-storage-decorator-filter

Filter decorator for redux-storage
JavaScript
26
star
7

redux-middleware-react-native-appstate

Glue AppState from react-native to Redux
JavaScript
21
star
8

babel-preset-modern-node

Babel preset for modern node apps
JavaScript
19
star
9

redux-storage-engine-localstorage

window.localStorage engine for redux-storage
JavaScript
19
star
10

ansible-vagrant

Simple helper to use ansible with vagrant
Python
14
star
11

bono

Simple 2d-framework and module collection for Monkey
Monkey
12
star
12

phpgsb

PHP implementation of the Google Safe Browsing API
PHP
10
star
13

redux-storage-merger-immutablejs

ImmutableJS compatible merger for redux-storage
JavaScript
10
star
14

redux-middleware-react-native-netinfo

Glue NetInfo from react-native to Redux
JavaScript
9
star
15

redux-storage-decorator-debounce

Delay and merge save opertations of redux-storage
JavaScript
8
star
16

RESTGuardian

Python and tornado based webserver to serve a MySQL via HTTP-REST
Python
5
star
17

redux-storage-decorator-immutablejs

Decorator for redux-storage to convert your state tree to ImmutableJS
Makefile
5
star
18

simpleflake-php

Distributed ID generation in *PHP* for the lazy.
PHP
5
star
19

redux-storage-merger-simple

Default merger for redux-storage
JavaScript
4
star
20

redis-highscore

Redis based highscore for your game / website / blog / ...
PHP
4
star
21

simpleflake-rs

Distributed ID generation in Rust for the lazy.
Rust
3
star
22

git-chiefs

Detects the chiefs for all remote branches
Shell
3
star
23

redux-middleware-oneshot

Create Redux actions from arbitraty sources out of middlewares
Makefile
3
star
24

credly-import-action

Import certificates from Credly into repo
Shell
3
star
25

monkey-wizard

Configure / inject third party libs into Monkey based projects
Monkey
2
star
26

ansible-ssh_known_hosts

Ansible role to manage /etc/ssh/ssh_known_hosts
2
star
27

uilog

Logging interface for somewhat pretty CLI apps
JavaScript
1
star
28

actions-20230213

Dockerfile
1
star
29

awsenv-example-env

Example environment for awsenv
1
star
30

CacheDecorator

Very simple caching decorator for all PHP objects
PHP
1
star
31

ansible-rotatingtor

Ansible role for your private rotating proxy.
1
star
32

docker-nginx

Dockerized nginx including h5bp best practices
Shell
1
star
33

redux-storage-engine-localstoragefakepromise

redux-storage-engine-localStorageFakePromise
JavaScript
1
star
34

monkey-shovel

Reusable Shovel tasks for projects based on Monkey
Python
1
star
35

game.racer

Pseudo 3D racing game written in Monkey-X
Monkey
1
star
36

docker-nginx-php-fpm

Add nginx to the official php:fpm-alpine image
Nginx
1
star