Search code examples
reactjsreduxredux-thunk

Why use dispatch to call a function in actions?


In my redux actions.js file i have the following two functions ::-

export const init = () => async dispatch => {
    dispatch({ type: TYPES.SET_LOADING });
    await dispatch(getConfig());
    await dispatch(getGenres());    
    dispatch({ type: TYPES.REMOVE_LOADING }); 
}

export const getConfig = () => async dispatch => {
    const res = await axios.get('https://api.lala.org/3/configuration?api_key=370');
    dispatch({
        type : TYPES.GET_CONFIG,
        payload : res.data
    });
}

I am just confused as to what is the use of await dispatch(getConfig()); ?

I understand when dispatch is used to send an action and a payload , but why is dispatch being used to call a function ? is it because dispatch is async and we need to use await ?


Solution

  • Normally you have to dispatch an action, which is just an object with a type (e.g. dispatch({ type: TYPES.SET_LOADING });). With redux-thunk as middleware, however, you can also use asynchronous functions with redux, e.g. for fetching data. Therefore, you pass the async function call as the parameter for dispatch (await dispatch(getConfig());). The async function needs to return another function which has now the dispatch function as the parameter (const getConfig = () => async dispatch => {...}.

    In that async function you can then dispatch actions.