Skip to content

Instantly share code, notes, and snippets.

@GuillaumeJasmin
Last active July 4, 2017 02:28
Show Gist options
  • Save GuillaumeJasmin/057cdd52607cee410fa7938e6c035347 to your computer and use it in GitHub Desktop.
Save GuillaumeJasmin/057cdd52607cee410fa7938e6c035347 to your computer and use it in GitHub Desktop.
In Redux, we create several codes with the same pattern for one or more properties. If the reducers have many properties, the work is very repeatable. This file makes it possible to write less code and save time
/*_________________________________________________________________
*
* Examples
*_________________________________________________________________
*/
/**
* React Components
*/
this.props.actions.setProperties({
foo: 'foooo',
bar: 'baz'
})
/**
* redux actions
*/
import {actionSetProperties} from './reduxSetProperty.js';
export const setProperties = actionSetProperties('SET_PROPERTY');
/**
* Warnin: if reduxSetProperty is used into multiple reducers, change the type name (SET_PROPERTY) for each reducers
*/
/**
* redux 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;
}
}
/*
* _________________________________________________________________
*/
/**
* reduxSetProperty.js
*/
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