Skip to content

Instantly share code, notes, and snippets.

@shivekkhurana
Created December 7, 2017 06:27
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shivekkhurana/42491dca912b9388e90f92541caeee16 to your computer and use it in GitHub Desktop.
Save shivekkhurana/42491dca912b9388e90f92541caeee16 to your computer and use it in GitHub Desktop.
Automate writing redux reducers
export default function keducer(prefix, actionMutationMap={}) {
return (state={}, action) => {
return actionMutationMap[action.type] ?
actionMutationMap[action.type](state, action.payload) :
action.type.indexOf(`${prefix}.`) === 0 ? {…state, …(action.payload)} : state
;
};
}
@shivekkhurana
Copy link
Author

Phonetic : "Kay-Deu-Cer"
Allow for a map like declaration of reducers.
Copies entire payload if no action definition is present, or run the definition if it exists.

ex:

export default keducer('users', {
  'users.signInSuccess': (state, {user, token}) => ({...state, user, token, loading: false});
})

export function signIn(username, password) {
  ...
  dispatch({type: 'users.signInSuccess', payload: {user: res.user, token: res.token}});
  ...
}

//--------------------------------------------------------------------------//
// This will work even without registering the action : 'users.loadSuccess'. 
// Welcome for the tons of time saved.
//-------------------------------------------------------------------------//
export function loadUserFromCache() {
  ...
  Promise(...)
    .then((user, token) => {
      dispatch({'type': 'users.loadSuccess', payload: {user, token}});   
    })
  ; 
  ...
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment