George Fourmouzis
George Fourmouzis

Reputation: 26

Setting initial state in Redux sub-reducers

I am getting to know the reducer composition concept in Redux, and I was confused about how the initial state should be set in the sub-reducers.

A similar question was this but it concerns only the top-level reducers for each part of the state tree.

As I understand it, each reducer should be supplying initial state for the part of the state tree it's responsible for.

For example, if I had a state tree like this:

{
  dashboard:{
    stats:{
      sales:23,
      purchases:22
    },
    messages:{
      unread:3,
      draft:5
    },
    //...etc
  },
  //...
}

And I had one top level reducer for dashboard, as well as reducers for stats and messages, should the initial state for the parts of the dashboard be set in the dashboard reducer, or in the reducers for each part, and if so, how would this code look like?

My initial thought was to implement the dashboard reducer like this:

const initialState = {
  stats: {},
  messages: {},
  //...
}

export default function dashboard(state = initialState, action) {
  switch (action.type) {
    case FETCH_STATS:
    case FETCH_STATS_SUCCESS:
    case FETCH_STATS_FAILURE:
      return {
        ...state,
        stats: stats(state.stats, action)
      }
    case FETCH_MESSAGES:
    case FETCH_MESSAGES_SUCCESS:
    case FETCH_MESSAGES_FAILURE:
      return {
        ...state,
        messages: messages(state.messages, action)
      }
      //...any other action cases
    default:
      const combined = combineReducers({
        stats,
        messages
      })
      return {
        ...state, //for any part without a reducer
        ...combined
      }
  }
}

Is my reasoning correct? Any improvement suggestions are also welcome.

Upvotes: 1

Views: 327

Answers (1)

Radio-
Radio-

Reputation: 3171

Either would work. The only thing that comes to mind is that, without an initial state, it doesn't really fit the definition of a Redux reducer; it would not work in isolation, since Redux expects the initial state to not be undefined.

In any case it's rather innocuous to set an initial state on the sub-reducer as

export default function stats(state = {}, action) {
    // ... whwtever
}

Upvotes: 1

Related Questions