redux-action-binder
A helper to easily and efficiently expose bound action creators.
Installation
npm install redux-action-binder
Usage
This was designed with "Ducks reducer bundles" in mind but regardless, it will bind all named functions located in a module. As an example, assuming a structure similar to this:
redux/
reducer.js // returns the combined reducer
actions.js // returns the bound actions (see below)
modules/
auth.js // reducer modules exporting action constants, actions and module reducer
login.js
posts.js
// actions.js; // extract actions from all modules;;; actionBinder;const getBoundActions = actionBindergetBoundActions;;
In the PostsContainer class:
; { return posts: stateposts ;} { return ;} // or to assign actions from multiple modules to the container... ; { return ; }
Note that getBoundActions returns an object who's properties are functions. Calling posts() the first time will invoke bindActionCreators on all post actions and subsequent calls will return the already bound actions. Actions are bound only once per each module.
IMPORTANT: By default, the current implementation imports all named functions found in the provided modules. In production builds this will not work if mangling is enabled. You must disable name mangling to use this, for example if using Webpack you can configure the Uglify plugin like this:
// Minify JS mangle: false
If you have name mangling enabled you must mark all of the action creator functions using the static string "@action name;"
, for example:
{ "@action loginSubmit"; return type: LOGIN_SUBMIT user pass}
The name following the @action marker will be used as the property name of the function. This way, even if the function names are mangled this will still work:
getBoundActions(dispatch).login().loginSubmit(user, pass)
To enable this feature you must configure the action binder prior to calling bindActions:
actionBinder;
IMPORTANT NOTE: See warning about testing below.
What gets bound
If not using annotations the actionBinder currently imports all named functions from the modules provided. If the modules include other functions you can tell the actionBinder to ignore them by providing a second argument:
actionBinder;
In this case it will ignore functions func1 and func2.
Warning about running tests
If you are running tests with a beforeEach that resets the store, don't forget that the action binder caches the bound functions. For this specific use case, you will need to reset
it and rebind the actions. For example, here is the redux/actions.js
that exposes the bound methods as well as the reset
function:
;;;; actionBinder;const getBoundActions = actionBindergetBoundActions; const resetActionBinder = { actionBinder; actionBinder;}; ;
Call the resetActionBinder method each time you reconfigure the store for your tests or the actions will be executing against a different store instance.