Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use dispatch vs return in actions?

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.

like image 278
Blueboye Avatar asked Sep 06 '25 21:09

Blueboye


1 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

like image 87
Mayank Pandeyz Avatar answered Sep 10 '25 12:09

Mayank Pandeyz