redux-create-actions is a library that helps construct FSA compliant action creators and massively decreasing the amount of boilerplate necessary to generate constants and action creators.
$ npm install --save redux-create-actions
or
$ yarn add redux-create-actions
Suppose we need to generate action creators and constants to fetch reddit posts and log out
// actions/reddit.jsimport{buildActions,createAction}from'redux-create-actions'const{ actions, constants}=buildActions('reddit',{logout:createAction('LOGOUT'),loadPosts:createAction('LOAD_POSTS',true)})exportconstconstantsexportdefaultactionsThebuildActions block noted in the example above would return an object with a shape of
{constants:{'LOGOUT':'@reddit/LOGOUT','LOAD_POSTS':'@reddit/LOAD_POSTS','LOAD_POSTS_START':'@reddit/LOAD_POSTS_START','LOAD_POSTS_SUCCESS':'@reddit/LOAD_POSTS_SUCCESS','LOAD_POSTS_FAILURE':'@reddit/LOAD_POSTS_FAILURE'},actions:{logout:Fn,loadPosts:Fn// loadPosts.start: Fn// loadPosts.success: Fn// loadPosts.failure: Fn}}Like in the example above, whenactionCreator is called withtrue as its second argument (async), it will generate three more action creators and constants for request tracking.
There are two utility functions exported from the root of the module.
createAction(constant[,async])
constant <string>async <boolean?>
Utility function for generating action creators
buildActions(namespace,actionMap)
namespace <string>actionMap <Object>
Utility function used to bulk construct actions and constants.
TheactionMap is a javascript object keyed with the action creator's name and a call to thecreateAction function
// actionMap{likeRepo:createAction('LIKE_REPO')}Redux brought along many great things to the world of software development, unfortunately that came with a bit of extra boilerplate. While the boilerplate is manageable repeating the same code time and time again grows tiresome, especially when it comes to writing constants and action creators.
Take a usual file that exports constants and action creators for both sync and async actions.
exportconstLOAD_POSTS='@home/LOAD_POSTS'exportconstLOAD_POSTS_REQUEST={START:'@home/LOAD_POSTS_REQUEST_START',SUCCESS:'@home/LOAD_POSTS_REQUEST_SUCCESS',FAILURE:'@home/LOAD_POSTS_REQUEST_FAILURE'}exportconstconstants={LOAD_POSTS,LOAD_POSTS_REQUEST}exportconstloadPosts=({ payload})=>({type:LOAD_POSTS, payload})exportconstloadPostsRequest={start:({ payload})=>({type:LOAD_POSTS_REQUEST.START, payload}),success:({ payload})=>({type:LOAD_POSTS_REQUEST.SUCCESS, payload}),failure:({ payload})=>({type:LOAD_POSTS_REQUEST.FAILURE, payload})}exportdefault{ loadPosts, loadPostsRequest}Writing action creators and constants like this quickly becomes very tedious work, and that's whereredux-create-actions comes in. Refactor the following modules with just
import{buildActions,createAction}from'redux-create-actions'const{ constants, actions}=buildActions('home',{loadPosts:createAction('LOAD_POSTS',true)})MIT