Created
May 18, 2017 18:10
-
-
Save GuillaumeJasmin/9869e9965b19446bf67415ecefd3966e to your computer and use it in GitHub Desktop.
In Redux, we create many code with the same pattern for update one or multiple properties. If the reducers has many property, the work is very repeatable. This make possible to write less code and save time
This file contains hidden or 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
/*_________________________________________________________________ | |
* | |
* Examples | |
*_________________________________________________________________ | |
*/ | |
/** | |
* Components | |
*/ | |
this.props.actions.setProperties({ | |
foo: 'foooo', | |
bar: 'baz' | |
}) | |
/** | |
* actions | |
*/ | |
import {actionSetProperties} from './reduxSetProperty.js'; | |
export const setProperties = actionSetProperties('SET_PROPERTY'); | |
/** | |
* Warnin: is reduxSetProperty is used into multiple reducers, change the type name (SET_PROPERTY) for each reducers | |
*/ | |
/** | |
* reducers | |
*/ | |
import {reducerSetProperies} from './reduxSetProperty.js'; | |
const initialState = { | |
foo: '...', | |
bar: '...' | |
} | |
export const myReducer = (state = initialState, action) => { | |
switch (action.type) { | |
case types.SET_PROPERTY: { | |
return reducerSetProperies(state, initialState, action) | |
} | |
default: | |
return state; | |
} | |
} | |
/* | |
* _________________________________________________________________ | |
*/ | |
export const actionSetProperties = type => properties => ({ | |
type, | |
properties | |
}); | |
export const reducerSetProperies = (state, initialState, action) => { | |
const nextState = {}; | |
for (let [key, value] of Object.entries(action.properties)) { | |
if (initialState[key] === undefined) { | |
console.error(`Reducer: key ${key} is undefined in initialState`); | |
}; | |
nextState[key] = value; | |
} | |
return { | |
...state, | |
...nextState | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment