Skip to content

Optional initialState

Jarl André Hübenthal edited this page Mar 21, 2019 · 6 revisions

An application built with typesafe-actions, where the RootState type is deduced based on the reducers with StateType among other things, and where each reducer sets its state parameter to a default initialState if not provided, should not be required to supply initialState in the createStore function.

Therefore the createStore function type has been changed so that it can either be CreateStore or CreateReduxLikeStore. The term "ReduxLikeStore" means that we couldn't just change the default behaviour and say that initialState is not required anymore, because old reducers then might crash if initialState is not supplied. Redux allows to not supply initialState, and it figures out the initialState by running the combined reducers on start.

A naive solution without any fix for this problem would be:

export const { dispatch, useGlobalState } = createStore<
  RootState,
  RootActions
>(reducers, reducers(undefined, { type: undefined}), enhancers);

And it works wonderfully. However, it is a concern that shouldn't need to be there at the first place.

So therefore you can now write:

export const { dispatch, useGlobalState } = (createStore as CreateReduxLikeStore)<
  RootState,
  RootActions
>(reducers, undefined, enhancers);

Which results in the exact same behaviour, but you don't have to think about initialState.

Clone this wiki locally