AnApprentice
AnApprentice

Reputation: 110940

How do I pass initial state to my reducers?

I have the following react-redux store:

let store;

const initStore = ({onRehydrationComplete}) => {

  store = createStore(
    combineReducers({
      ...reactDeviseReducers,
      form: formReducer,
      router: routerReducer,
      apollo: apolloClient.reducer(),
      cats
    }),
    {},
    compose(
      applyMiddleware(
        thunk,
        routerMiddleware(history),
        apolloClient.middleware()
      ),
      autoRehydrate(),
      window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()
    )
  );

  persistStore(store, {
    blacklist: [
      'form'
    ]
  }, onRehydrationComplete);

  return store;
};

How can I pass initial state to the reducers and to my app?

Upvotes: 0

Views: 1485

Answers (1)

Andrew Li
Andrew Li

Reputation: 57924

You can pass your initial state as the second argument of createStore:

createStore(reducer, [preloadedState], [enhancer])

  1. [preloadedState] (any): The initial state. You may optionally specify it to hydrate the state from the server in universal apps, or to restore a previously serialized user session. If you produced reducer with combineReducers, this must be a plain object with the same shape as the keys passed to it. Otherwise, you are free to pass anything that your reducer can understand.

I would personally suggest setting initial state per each reducer, specific to that reducer. For example, in a Todo App:

const initialState = [
    { text: "This is a todo!", completed: false }
];

function todos(state = initialState, action) {
    ...
}

Here, the todos reducer only knows about it's certain "slice" of state, not the whole application state. It only knows about an array of todos, not everything else in state. Though, in this case, this might not be possible

Upvotes: 3

Related Questions