Last active
March 5, 2019 11:48
-
-
Save alexengrig/89fd5f616031ebb7165b1dc793a22046 to your computer and use it in GitHub Desktop.
Function of create a reduce function for Redux store
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
function createReduce(reducer = {}, initialState) { | |
return (state = initialState, action) => { | |
const { type: actionType } = action; | |
const func = reducer[actionType]; | |
const newState = typeof func === 'function' ? func.call(reducer, state, action) : undefined; | |
return newState !== undefined ? newState : state; | |
}; | |
} | |
// example | |
const SOME_ACTION = 'SOME_ACTION'; | |
const reducer = { [SOME_ACTION]: (state, { payload }) => payload }; | |
const reduce = createReduce(reducer); | |
const state = false; | |
const action = { type: SOME_ACTION, payload: true }; | |
const newState = reduce(state, action); | |
// => newState is true |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment