Alternative to Switch Statements
Learn about the alternatives to using switch statements.
In Redux, most reducers
are just switch
statements over action.type
. Since the switch
syntax can be hard to read and prone to errors, a few libraries try to make writing reducers easier and cleaner.
While it is most common for a
reducer
to examine thetype
property of the action to determine if it should act, in some cases, other parts of the action object are used. For example, you might want to show an error notification on every action with an error in the payload.
The redux-actions
library provides the handleActions()
utility function for reducer generation:
import { handleActions } from 'redux-actions';
//declare state
const initialState = [];
//reducer
const recipesReducer = handleActions({
//case add_recipe
[ADD_RECIPE]: (recipes, action) =>
//combine recipes
recipes.concat(action.payload),
//case remove_recipe
[REMOVE_RECIPE]: (recipes, action) =>
//remove the given recipe
recipes.filter(recipe => recipe.id === action.payload)
}, initialState);
export default recipesReducer;
If you are using Immutable.js, you might also want to look at the redux-immutablejs library, which provides you with createReducer()
and combineReducers()
functions that are aware of Immutable.js features like getters and setters. Immutable.js is explained in the following modules.
Get hands-on with 1400+ tech skills courses.