Redux Async Initial State

raw JSON →
0.3.0 verified Sat Apr 25 auth: no javascript maintenance

A Redux middleware for loading initial application state asynchronously from sources like HTTP APIs or React Native's AsyncStorage. Current version 0.3.1, maintained with intermittent updates. Provides `outerReducer`, `innerReducer`, and `middleware` to handle async state loading and loading/error UI state. Differentiates from manual promise handling by offering a structured middleware approach that integrates with Redux's store creation. Compatible with Redux 4.0.0+.

error TypeError: middleware is not a function
cause Calling `middleware` as a function without argument or using it directly in applyMiddleware without invoking it first.
fix
Use applyMiddleware(middleware(loadStore))
error Uncaught Error: Expected the nextReducer to be a function
cause The outerReducer received something that is not a reducer (e.g., plain object or undefined).
fix
Ensure outerReducer wraps a valid reducer, e.g., outerReducer(combineReducers({...}))
error Action 'REDUX_ASYNC_INITIAL_STATE' not recognized by reducer
cause Missing `outerReducer` wrapper, so the store's reducer does not handle the async state replacement action.
fix
Wrap your combined reducer with outerReducer.
breaking Using this middleware with Redux 4.0.0+ requires version 0.3.0+. Older versions may cause errors.
fix Update to version >=0.3.0
gotcha The `middleware` function must be called with a `loadStore` argument that returns a Promise. Omitting it or using a non-Promise will cause runtime error.
fix Ensure loadStore returns a Promise (e.g., using async/await or explicit new Promise).
gotcha The `outerReducer` must wrap your combined reducer. Failure to do so will break state replacement when async state loads.
fix Always use: const rootReducer = outerReducer(combineReducers({...}));
deprecated Importing via `require('redux-async-initial-state')` is still supported but ESM imports are preferred for tree-shaking.
fix Switch to import { ... } from 'redux-async-initial-state'
npm install redux-async-initial-state
yarn add redux-async-initial-state
pnpm add redux-async-initial-state

Sets up Redux store with async initial state loading via HTTP fetch.

import { createStore, applyMiddleware, combineReducers, compose } from 'redux';
import { outerReducer, innerReducer, middleware } from 'redux-async-initial-state';

const reducer = outerReducer(combineReducers({
  // ... your reducers
  asyncInitialState: innerReducer,
}));

const loadStore = () => {
  return new Promise(resolve => {
    fetch('/api/initial-state')
      .then(response => response.json())
      .then(resolve);
  });
};

const store = createStore(
  reducer,
  compose(applyMiddleware(middleware(loadStore)))
);