Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redux - how to call an action creator from inside another action creator?

Tags:

reactjs

redux

I have the following action creator:

export function foo(param) {
    ...
}

and I want to call it from an adjacent action creator (in the same file) like this:

export function bar(param){
    return (dispatch, getState) => {
        dispatch({
            type: ATYPE.SET_DO_THIS_BEFORE_FOO,
            payload: param
        });

        foo(param);
    }
}

but the foo action creator is not firing from inside bar. Is there any way to do this?

like image 230
JoeTidee Avatar asked Mar 31 '17 01:03

JoeTidee


People also ask

How do you call an action creator using react Redux?

Using mapDispatachToProps function with connect higher order component, same as in class based components. Using useDispatch hook provided by react-redux . If you want to use this hook, then you need to import it from the react-redux package. This hook returns a function that can be used to dispatch actions.

Can Redux action dispatch another action?

Dispatch actions using Redux-saga library To run many async instructions one after the other and also maintain readability of the code, we can dispatch an action that will then trigger a saga. We can use redux-saga library in the same way. Using the saga, we can dispatch actions with the put effect.

Is it possible to trigger a Redux action from outside a component?

If you need to dispatch actions from outside a React component, the same technique will work: import the store, then call store. dispatch() , passing the action you need to dispatch. It works the same as the dispatch function you get from props via react-redux's connect function.


1 Answers

According to your example, it seems that you're already using redux-thunk. If that's the case, the only thing that you're forgetting is to dispatch the action created by your action creator:

dispatch(foo(param));
like image 147
Buzinas Avatar answered Oct 03 '22 06:10

Buzinas