Redux Async Initial State

Redux middleware for async loading of initial app state.

build status npm version

npm install --save redux-async-initial-state

What? Why?

With redux it is quite simple to synchronously load initial state, i.e. from localStorage:

...
const initialState = JSON.parse(localStorage.getItem('state'));
const store = storeCreator(reducer, initialState);

But it becomes quite complicated to do it asynchronously, i.e. from server or from async storage, like in React Native. This middleware do it for you.

Usage

  1. Add package

npm install --save redux-async-initial-state
  1. Change your reducer and add middleware:

before:

import { createStore, combineReducers } from 'redux'
import * as reducers from 'reducers'

const reducer = combineReducers(reducers)
const store = createStore(reducer)

After

Partial replace

In case when you're loading only part of your store initially, you can add getCurrentState argument in loadStore function. So, if you have some complex shape of your reducer and you need to replace only some of keys in your store (currentUser in example below):

Reducer

The shape of innerReducer is:

You can add it to you reducer if you want to handle loading state, i.e. to show loading spinner. Here is React example (it uses reducer, described above):

Last updated

Was this helpful?