Skip to content

Instantly share code, notes, and snippets.

@luqmaan
Last active August 2, 2016 16:21
Show Gist options
  • Save luqmaan/f31f66c9cf4375695d4b0de5ff3996a6 to your computer and use it in GitHub Desktop.
Save luqmaan/f31f66c9cf4375695d4b0de5ff3996a6 to your computer and use it in GitHub Desktop.

Redux Action Registry

Create an object with all your action creators. This makes it easier to debug your application, since now you can dispatch actions from the console or from the Redux Devtools Extension.

Usage

ActionRegistry['data/accountBalance'].SET_ACCOUNT_BALANCE // "ordoro/data/accountBalance/SET_ACCOUNT_BALANCE"
ActionRegistry['data/accountBalance'].setAccountBalance(3) // {type: "ordoro/data/accountBalance/SET_ACCOUNT_BALANCE", payload: 3}

store.dispatch(ActionRegistry['data/accountBalance'].setAccountBalance(3));  // state changes

image

It works by using webpack's require.context to require all the modules from a certain directory. This means it works even if your actions are very nested. It also means you don't have to manually import your actions into the action registry.

⚠️

Don't use this in your actual code. Only use this for debugging. Regular imports are much more explicit and aren't a hack:

import {setAccountBalance} from 'redux/actions/data/accountBalance



### Setup

```js
function requireAllActions(requireContext) {
    return requireContext.keys()
        .reduce((prev, key) => {
            const moduleName = key.replace(/.js$/, '').replace(/^.\//, '');
            return {
                ...prev,
                [moduleName]: requireContext(key),
            };
        }, {});
}

window.ActionRegistry = requireAllActions(require.context('../redux/actions', true, /.js$/));

ActionRegistry['data/accountBalance'].SET_ACCOUNT_BALANCE // "ordoro/data/accountBalance/SET_ACCOUNT_BALANCE"
ActionRegistry['data/accountBalance'].setAccountBalance(3) // {type: "ordoro/data/accountBalance/SET_ACCOUNT_BALANCE", payload: 3}

Based on

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