Passing objects in actions vs attributes
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?
Answer
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.
Related Questions
- → Import statement and Babel
- → should I choose reactjs+f7 or f7+vue.js?
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → .tsx webpack compile fails: Unexpected token <
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → React Native with visual studio 2015 IDE
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM
- → How do I determine if a new ReactJS session and/or Browser session has started?
- → Alt @decorators in React-Native
- → How to dynamically add class to parent div of focused input field?