Skip to content

Instantly share code, notes, and snippets.

@davidsharp
Created November 28, 2016 17:20
Show Gist options
  • Select an option

  • Save davidsharp/372a9a6e91bc62cf7912b4004d2b964e to your computer and use it in GitHub Desktop.

Select an option

Save davidsharp/372a9a6e91bc62cf7912b4004d2b964e to your computer and use it in GitHub Desktop.
A mad two-line helper for generating flexible Redux Action Creators with an inflexible naming schema
const ah/*ActionHelper*/ = (g='DEFAULT',n='ACTION') => (o={}) => (Object.assign({type:`${g}_${n}`.toUpperCase()},o))
const ach/*ActionCreatorHelper*/ = (n,arr) => (arr.reduce((a,b)=>Object.assign(a,{[b]:ah(n,b)}),{}))
/*
Example usage
//Helper strings
const C='create',R='read',U='update',D='delete',S='success',F='failure';
const Sync = ach('sync',[S,F]);
const CrudApp = ach('data',[C,R,U,D]);
const User = ach('user',['signin','signout']);
const justAnActionCreator = ah('sync','success');
//Generates objects like
// Sync = {success: [fn] , failure: [fn] }
// Sync.success = object =>( { type:'SYNC_SUCCESS' , ...object} )
// justAnActionCreator == Sync.success
*/
@davidsharp

Copy link
Copy Markdown
Author

On a side note, you can probably replace those Object.assigns with object rest params, but Node support for it is a bit weak (doesn't work in my Node 6.8.0, that's for sure), depending on your version, so I didn't test it.

Babel will deal with it though, so if you really wanna save a few bytes and up your ES6+ game, go for it!

@davidsharp

davidsharp commented Nov 29, 2016

Copy link
Copy Markdown
Author

Might build this out into an npm module (I'm thinking I'll rename it 'Objection!', or more specifically redux-objection)

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