Redux Async Initial State
Redux middleware for async loading of initial app state.
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;const store = ;
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
- Add package
npm install --save redux-async-initial-state
- Change your reducer and add middleware:
before:
const reducer = const store =
After
;;; // We need outerReducer to replace full state as soon as it loadedconst reducer = asyncInitialState; // Load state function// Should return promise that resolves application stateconst loadStore = { return { ; };} const store = ;
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):
const loadStore = { return { ; };}
Reducer
The shape of innerReducer
is:
loaded: false loading: false error: false
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):
;; @Component { if thispropsloading return <div>Loading...</div> return ...; }