Skip to content
Advertisement

Cannot call Action within another Action

I am having trouble understanding this behaviour

I have an action defined like this

import { whatever } from './kitty';

export const onDone = foo => dispatch => {
    whatever(foo);
    dispatch({
        type: ON_DONE,
    });
};

and whatever() is defined like this

export const whatever = foo => dispatch => {
    console.log('I DO NOT GET LOGGED');
    dispatch({
        type: DO_WHATEVER,
        payload: foo
    });
};

I expect whatever() to be executed, but it is not. Why is that?

Advertisement

Answer

Both onDone and whatever here are not “actions”, they are “action creators”. They are functions that return an action (“thunk actions” in this case). An action here being something that can be dispatched to the redux store.

Them being action creators means: if you call them, you have an action, but that’s like writing a letter. You now have a letter. It will be lying around on your table until you actually do something with it.

What do you do with an action for it to have any effect in redux? You dispatch it to the store.

So you would have to actually dispatch the action created by your whatever action creator:

export const onDone = foo => dispatch => {
    dispatch(whatever(foo));
    dispatch({
        type: ON_DONE,
    });
};

PS: another answer suggests to call whatever(foo)(dispatch). While that technically works and is part of what the redux-thunk middleware does internally, it does not fit the redux data flow model and is not the intended way of usage by the authors of the library. Please don’t do this.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement