2

Is there a better way for writing the following code:

export const getItemsSuccess = (state, entity, payload) => {
  const {count, rows} = payload

  const clonedState = {...state}
  clonedState[entity] = {...clonedState[entity], count, rows}

  return {
    ...clonedState,
  }
}
Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
Yaniv Or
  • 57
  • 1
  • 6

1 Answers1

1

For simple cases like this, I tend to inline this into a single object literal. It makes the logic a bit easier to follow.

export const getItemsSuccess = (state, entity, {count, rows}) => {
  return {
    ...state,
    [entity]: {
      ...state[entity],
      count,
      rows,
    }
  }
}
  1. Use deconstructing assignment of the payload {count, rows}. This makes it clear the properties the payload should have at a glance, and makes them easy to use in the reducer body.

  2. Only clone objects once. You have const clonedState = { ...state } and also return { ...clonedState } where return clonedState would do fine (or returning a constructed literal like I have).

  3. Don't create local variables for values only used once in the final state. This makes it easier to follow the flow of the reducer.

  4. Constructing the whole new state as a single object literal makes it easy to tell what going on and how the data is changing.

This is a somewhat subjective thing, but I think this style has some merit.

Alex Wayne
  • 178,991
  • 47
  • 309
  • 337