When to use dispatch vs return in actions?

Viewed 367

I am a bit confused when it comes to dispatching actions. In the actions sometimes I see this:

export const getConfig = () => dispatch => {
    const res = await axios.get('/api/users');
    dispatch({
        type : TYPES.GET_CONFIG,
        payload : res.data
    });
}

and sometimes I see:

export const getConfig = () => {
    const res = await axios.get('/api/users');

    return{
        type : TYPES.GET_CONFIG,
        payload : res.data
    };
}

Are they both same? or they have their own use cases? When to use what?

Thanks.

2 Answers

By default actions in Redux are dispatched synchronously, which is a problem for any non-trivial app that needs to communicate with an external API or perform side effects.

Ex:

return{
    type : TYPES.GET_CONFIG,
    payload : res.data
};

Redux Thunk is a middleware that lets you call action creators that return a function instead of an action object. That function receives the store's dispatch method, which is then used to dispatch regular synchronous actions inside the body of the function once the asynchronous operations have completed.

Ex:

dispatch({
    type : TYPES.GET_CONFIG,
    payload : res.data
});

thunk is a concept in programming where a function is used to delay the evaluation/calculation of an operation.

Explanation Reference

Redux does not supporting side effects out of the box. For side effects in Redux you have to use additional libraries. For example:

  • Redux-thunk (first example in your question);
  • Redux-saga;
  • Redux-observable.

In other words, if you need side effects (requests to API, etc.) or you want to call two or more actions, then use the first code example, if not - the second.

I hope I could help you.

Related