According to Redux documentation, creating actions and action creators is necessary. Here's an example:
function addTodo(filter) {
return {
type: SET_VISIBILITY_FILTER,
filter
}
}
Next step is to write reducers, like this:
function todoApp(state = initialState, action) {
switch (action.type) {
case SET_VISIBILITY_FILTER:
return Object.assign({}, state, {
visibilityFilter: action.filter
});
}
}
The action can be invoked using dispatch:
store.dispatch(addTodo("Ask question on stackoverflow"));
Each action corresponds to a specific reducer; the purpose of the action is to select a reducer and provide input data for it.
What if we directly link actions with reducers and action creators with functions that produce reducers? Then dispatch
would only take a single argument, a reducer/action of type State => State
:
// Action/reducer. (Parametrised state transformer)
const addTodo = text => state => {
return Object.assign({}, state, {
visibilityFilter: action.filter
});
}
// Dispatch takes the action/reducer argument
store.dispatch(addTodo("Ask question on stackoverflow"));
Serialization of actions may not be possible in this scenario, but it eliminates boilerplate action creators and clarifies the connection between actions and reducers. In Typescript, you also gain data type checking in actions, which is challenging to achieve otherwise, as discussed here.
Are there any other reasons for keeping actions as data that I might be overlooking?