I'm currently learning Redux on codecademy and encountered something that feels redundant.
The course gives the following example on excessive ways to call dispatches:
store.dispatch({type:'toggle'});
store.dispatch({type:'toggle'});
store.dispatch({type:'toggle'});
In most Redux applications, action creators are used to reduce this repetition and to provide consistency. An action creator is simply a function that returns an action object with a type property. They are typically called and passed directly to the store.dispatch() method resulting in fewer errors and an easier-to-read dispatch statement.
The above code could be rewritten using an action creator called toggle() like so:
const toggle = () => {
return { type: "toggle" };
}
store.dispatch(toggle()); // Toggles the light to 'off'
store.dispatch(toggle()); // Toggles the light back to 'on'
store.dispatch(toggle()); // Toggles the light back to 'off'
My question is, why not simplify this Action Creator callback function that returns an object, by just creating an object like so?
const toggle = { type: toggle }
store.dispatch(toggle);
store.dispatch(toggle);
store.dispatch(toggle);
CodePudding user response:
const toggle = Object.freeze({ type: "toggle" })
does indeed work fine and would be appropriate for this particular action. However, often an action does carry a payload, and to create actions with different payload values a function would be used, e.g.
function openSection(index) {
return {type: "open", index};
}
that you would call like
store.dispatch(openSection(1))
// or
e => store.dispatch(openSection( e.target.dataset.index))