0

In our Product we use Angular 6 together with NgRX 6. Instead of defining our constants as export const strings, we use an object to encapsulate them:

export const ACTION_CONSTANTS = {
    'OPEN_MODAL'                              : 'OPEN_MODAL',
    'CLOSE_MODAL'                             : 'CLOSE_MODAL',
    'OPEN_TOOLTIP'                            : 'OPEN_TOOLTIP',
    'CLOSE_TOOLTIP'                           : 'CLOSE_TOOLTIP',
    ...
};

As the ACTION_CONSTANTS object gets bigger and prefixes get longer ('DROPDOWN_ACTION_SKIP_SET_INIT_STATE'), I would prefer to nest constants e.g. by feature:

export const ACTION_CONSTANTS = {
    'MODAL' : {
        'OPEN'                                : 'MODAL.OPEN',
        'CLOSE'                               : 'MODAL.CLOSE'
    },
    'TOOLTIP' : {
        'OPEN'                                : 'TOOLTIP.OPEN',
        'CLOSE'                               : 'TOOLTIP.CLOSE'
    },
    ...
};

Is it a good idea or are there any downsides? I could not find anything on formatting constants on the Redux FAQ.

Florian Gössele
  • 4,376
  • 7
  • 25
  • 49

2 Answers2

2

I don't think it is a bad idea, as long as you're able to keep it all organized. But I would suggest grouping your actions into different files. I find this the best way to keep things organized.

--ActionsFile   
  -modalActions.js   
  -toolTipAction.js
adam.k
  • 622
  • 3
  • 15
  • Imho a downside of this is that action constants could be equal in a large project without noticing (as they are just strings) and activate 2 reducers. – Florian Gössele Sep 25 '18 at 10:59
0

I usually keep actions in different files, roughly aligned with models & reducers. And i have a naming convention like:

ACTION_MODEL_OUTCOME

So, for example, to load model of type ProductGroup i would have actions:

export const ActionTypes = {
LOAD_PRODUCTGROUP: enforceUnique("[ProductGroup] Laod ProductGroup"),
LOAD_PRODUCTGROUP_SUCCESS: enforceUnique("[ProductGroup] Load ProductGroup Success")
LOAD_PRODUCTGROUP_FAILURE: enforceUnique("[ProductGroup] Load ProductGroup Failure")
}

enforceUnique is a function that caches all registered actions and make sure there are no duplicates across the whole app.

Now, when you import actions for certain model, you import only those from file you need (e.g. import ProductGroupActionTypes from 'actions/ProductGroupActions') and use them like ProductGroupActionTypes.LOAD_PRODUCTGROUP.

Usually, first one (without outcome suffix) is the one to initiate action and set some pending flag in reducer to show loader and also to initiate http calls in @Effects.

Second one, with success suffix is handled in reducer to change state.

Third one is error handling, whatever way you want to do it.

dee zg
  • 13,793
  • 10
  • 42
  • 82