GithubHelp home page GithubHelp logo

marvinhagemeister / redux-persist Goto Github PK

View Code? Open in Web Editor NEW

This project forked from rt2zz/redux-persist

0.0 3.0 0.0 311 KB

persist and rehydrate a redux store

License: MIT License

JavaScript 100.00%

redux-persist's Introduction

Redux Persist

Persist and rehydrate a redux store.

Redux Persist is performant, easy to implement, and easy to extend.

npm i --save redux-persist

build status npm version npm downloads

Basic Usage

Basic usage requires adding a few lines to a traditional redux application:

import {compose, applyMiddleware, createStore} from 'redux'
import {persistStore, autoRehydrate} from 'redux-persist'

// add `autoRehydrate` as an enhancer to your store (note: `autoRehydrate` is not a middleware)
const store = createStore(
  reducer,
  undefined,
  compose(
    applyMiddleware(...),
    autoRehydrate()
  )
)

// begin periodically persisting the store
persistStore(store)

For per reducer rehydration logic, you can opt-in by adding a handler to your reducer:

import {REHYDRATE} from 'redux-persist/constants'
//...
case REHYDRATE:
  var incoming = action.payload.myReducer
  if (incoming) return {...state, ...incoming, specialKey: processSpecial(incoming.specialKey)}
  return state

You may also need to configure the persistence layer, or take action after rehydration has completed:

persistStore(store, {blacklist: ['someTransientReducer']}, () => {
  console.log('rehydration complete')
})

And if things get out of wack, just purge the storage

persistStore(store, config, callback).purge()

API

Full API

persistStore(store, [config, callback])

  • arguments
    • store redux store The store to be persisted.
    • config object
      • blacklist array keys (read: reducers) to ignore
      • whitelist array keys (read: reducers) to persist, if set all other keys will be ignored.
      • storage object a conforming storage engine.
      • transforms array transforms to be applied during storage and during rehydration.
      • debounce integer debounce interval applied to storage calls (in miliseconds).
      • keyPrefix string change localstorage default key (default: reduxPersist:) Discussion on why we need this feature ?
    • callback function will be called after rehydration is finished.
  • returns persistor object

persistor object

  • the persistor object is returned by persistStore with the following methods:
    • .purge(keys)
      • keys array An array of keys to be purged from storage. If not provided all keys will be purged.
    • .rehydrate(incoming, options)
      • incoming object Data to be rehydrated into the store.
      • options object If serial:true, incoming should be a string, that will be deserialized and passed through the transforms defined in the persistor.
      • Manually rehydrates the store with the passed data, dispatching the rehydrate action.
    • pause()
      • pauses persistence
    • resume()
      • resumes persistence

autoRehydrate(config)

  • This is a store enhancer that will automatically shallow merge the persisted state for each key. Additionally it queues any actions that are dispatched before rehydration is complete, and fires them after rehydration is finished.
  • arguments
    • config object
      • log boolean Turn on debug mode. Default: false.
      • stateReconciler function override the default shallow merge state reconciliation.

constants

  • import * as constants from 'redux-persist/constants'. This includes REHYDRATE and KEY_PREFIX.

Alternate Usage

getStoredState / createPersistor

If you need more control over persistence flow, you can implement getStoredState and createPersistor. For example you can skip autoRehydrate and directly pass restoredState into your store as initialState:

import {getStoredState, autoRehydrate, createPersistor} from 'redux-persist'

const persistConfig = { /* ... */ }

getStoredState(persistConfig, (err, restoredState) => {
  const store = createStore(reducer, restoredState)
  const persistor = createPersistor(store, persistConfig)
})

Secondary Persistor

import {persistStore, createPersistor} from 'redux-persist'
const persistor = persistStore(store) // persistStore restores and persists
const secondaryPersistor = createPersistor(store, {storage: specialBackupStorage}) // createPersistor only persists

Storage Engines

  • localStorage (default) web
  • sessionStorage
  • localForage (recommended) web, see usage below
  • AsyncStorage for react-native
  • redux-persist-node-storage for use in nodejs environments.
  • custom any conforming storage api implementing the following methods: setItem getItem removeItem getAllKeys. [example]
// sessionStorage
import { persistStore } from 'redux-persist'
import { asyncSessionStorage } from 'redux-persist/storages'
persistStore(store, {storage: asyncSessionStorage})

// react-native
import {AsyncStorage} from 'react-native'
persistStore(store, {storage: AsyncStorage})

// web with recommended localForage
import localForage from 'localForage'
persistStore(store, {storage: localForage})

Transforms

Transforms allow for arbitrary state transforms before saving and during rehydration.

  • immutable - support immutable reducers
  • compress - compress your serialized state with lz-string
  • encrypt - encrypt your serialized state with AES
  • filter - store or load a subset of your state
  • filter-immutable - store or load a subset of your state with support for immutablejs
  • expire - expire a specific subset of your state based on a property
  • custom transforms:
import { createTransform, persistStore } from 'redux-persist'

let myTransform = createTransform(
  // transform state coming from redux on its way to being serialized and stored
  (inboundState, key) => specialSerialize(inboundState, key),
  // transform state coming from storage, on its way to be rehydrated into redux
  (outboundState, key) => specialDeserialize(outboundState, key),
  // configuration options
  {whitelist: ['specialReducer']}
)

persistStore(store, {transforms: [myTransform]})

Migrations

One challenge developers encounter when persisting state for the first time is what happens when the shape of the application state changes between deployments? Solution: redux-persist-migrate

Action Buffer

A common mistake is to fire actions that modify state before rehydration is complete which then will be overwritten by the rehydrate action. You can either defer firing of those actions until rehydration is complete, or you can use an action buffer.

Why Redux Persist

  • Performant out of the box (uses a time iterator and operates on state partials)
  • Keeps custom rehydration logic in the reducers (where it intuitively belongs)
  • Supports localStorage, react-native AsyncStorage, or any conforming storage api

Because persisting state is inherently stateful, persistStore lives outside of the redux store. Importantly this keeps the store 'pure' and makes testing and extending the persistor much easier.

About Auto Rehydrate

autoRehydrate is a store enhancer that automatically rehydrates state.

While auto rehydration works out of the box, individual reducers can opt in to handling their own rehydration, allowing for more complex operations like data transforms and cache invalidation. Simply define a handler for the rehydrate action in your reducer, and if the state is mutated, auto rehydrate will skip that key.

Auto rehydrate is provided as a convenience. In a large application, or one with atypical reducer composition, auto rehydration may not be convenient. In this case, simply omit autoRehydrate. Rehydration actions will still be fired by persistStore, and can then be handled individually by reducers or using a custom rehydration handler.

redux-persist's People

Contributors

rt2zz avatar marvinhagemeister avatar greenkeeperio-bot avatar andarist avatar rufman avatar af avatar lkay avatar klathmon avatar unindented avatar zalmoxisus avatar morlay avatar andreaspsson avatar cretezy avatar scic avatar dsernst avatar dxiao avatar domlazic avatar edy avatar fkrauthan-hyperwallet avatar gabceb avatar actra-gschuster avatar gasp avatar doxxx avatar handtrix avatar ianvs avatar jasonmerino avatar joeybaker avatar jonespen avatar gnoff avatar moharu avatar

Watchers

James Cloos avatar  avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.