Passing objects in actions vs attributes

- 1 answer

Ad

In the examples I saw in the redux repo, it seems like the action objects always contain the attributes of the state we are creating/editing rather than passing in the object directly. For example

/* In the action creator */
export function addTodo(text) {
  return { type: types.ADD_TODO, text }
}

/* In the reducer */
....
case ADD_TODO:
  return [
    {
      id: state.reduce((maxId, todo) => Math.max(todo.id, maxId), -1) + 1,
      completed: false,
      text: action.text
    }, 
    ...state
  ]

Is there any particular advantage to doing it this way instead of, say, passing a 'todo' object directly in the action and adding any missing elements in the reducer?

I am working on an app where the object being passed in has many attributes and I find that I have to repeat extracting these attributes from the action in every reducer function. Isn't it easier to have, say in the previous example, action.todo to be set to the relevant object and have the reducer only add in whatever attributes are missing (such as the id)?

Is this some kind of convention/pattern that I am failing to grasp?

Ad

Answer

Ad

Generally I think your actions should be as simple as possible, conveying only the minimum amount of information they need to. But you can certainly change the structure of your actions to a format more convenient to process. A common pattern is to point to all the data with a payload key. e.g.

    /* In the action creator */
    export function addTodo(text, date, priority) {
      return {
        type: types.ADD_TODO,
        payload: {
          text,
          date,
          priority
        }
      };
    }

    /* In the reducer */
    case ADD_TODO:
      return [
        Object.assign({}, action.payload, {
          id: newId()
        }, 
        ...state
      ];

Your payload forms the basis of your todo object. Instead of extracting several attributes, you're only extracting one.

Ad
source: stackoverflow.com
Ad