Last active
November 4, 2019 22:48
-
-
Save samholmes/d44dc930c49169ca578bf8861649065d to your computer and use it in GitHub Desktop.
An example for a helper function to write clean reducers.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Rather than this | |
function reducer(state, action) { | |
switch (action.type) { | |
case 'TODO_ADD': { | |
return applyAddTodo(state, action) | |
} | |
case 'TODO_TOGGLE': { | |
return applyToggleTodo(state, action) | |
} | |
default: | |
return state | |
} | |
} | |
// Create a map of action types to reducer. | |
// Pass that map to a function which returns a reducer of the action type. | |
const reducer = (reducerOf => (state, action) => | |
(reducerOf[action.type] || (() => state))(state, action))({ | |
TODO_ADD: applyToggleTodo, | |
TODO_TOGGLE: applyToggleTodo, | |
}) | |
// Make less terse and more resusable with a dedicated mapActionToReducer function | |
const mapActionToReducer = reducerOf => (state, action) => { | |
const reducer = reducerOf[action.type] | |
return reducer ? reducer(state, action) : state | |
} | |
// Use helper function for clean | |
const reducer = mapActionToReducer({ | |
TODO_ADD: applyToggleTodo, | |
TODO_TOGGLE: applyToggleTodo, | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment