1

I have a logical issue, whether i should make a multiple function calls into response of each callback inside an actions:

export const myAction= () => (distaptch, getState) => {
    callFunctionA(function(e){
        if(e){
            dispatch(eventA(e));

            callFunctionB(function(e){

                dispatch(eventB(e));

                callFunctionC(function(e){

                    dispatch(eventC(e));
                });
            });
        }
    });
}

or i might want to move those calls into redux reducers and call every next function from there?

const reducer = (state={}, action) => {
  switch (action.type) {
    case 'EVENT_A':

      callFunctionB(action.e);

      return state;
    case 'EVENT_B':

        callFunctionC(action.e);
        return state;   
    default:
      return state
  }
}

Second approach looks to me like anti-pattern which leads to spaghetti code... Maybe i am wrong?

ArkadyB
  • 1,265
  • 1
  • 19
  • 37

1 Answers1

1

You're correct in assuming that dispatching actions in the reducer is an anti-pattern. The reasons are mentioned pretty succinctly in this post.

From the Redux documentation:

Things you should never do inside a reducer:

Mutate its arguments;

Perform side effects like API calls and routing transitions;

(Call non-pure functions, e.g. Date.now() or Math.random().

[...] For now, just remember that the reducer must be pure. Given the same arguments, it should calculate the next state and return it. No surprises. No side effects. No API calls. No mutations. Just a calculation.

You can look into Redux-Saga to handle asychronous flow to avoid the callback hell of the actions that you show in your first example.

Community
  • 1
  • 1
Yo Wakita
  • 5,322
  • 3
  • 24
  • 36
  • It does the same as await/async for thunk? – ArkadyB Mar 20 '17 at 20:01
  • Here is a post that details the differences/similarities between async/await with redux-thunk vs redux-saga. http://stackoverflow.com/questions/34930735/pros-cons-of-using-redux-saga-with-es6-generators-vs-redux-thunk-with-es7-async/34933395 – Yo Wakita Mar 20 '17 at 20:09