Search code examples
reactjsasync-awaitreact-reduxredux-thunk

Understanding async dispatch actions using redux thunk


I was just going though the files that dispatches ACTIONS in a reactjs app and basically came across the following function::-

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

I am a bit confused as to what the async is doing ahead of the dispatch , i am used to seeing normal vanilla javascript async functions like so:

anasyncfunc = async () => { 
   // write you're code here
}

But the above code confuses me a little. Can somebody please explain this to me.


Solution

  • A function which uses the await keyword must me marked with async which you have pointed out in your example

    anasyncfunc = async () => { 
       // write you're code here
    }
    

    In this function we can now use await since it was marked with async.

    In the case of the thunk, we are effectively creating an outer function called init which when called will return an anonymous function. This anonymous function will accept dispatch as an argument and will make use of the await keyword, and as such needs to be marked with the async keyword.

    In short, we really are just creating a function which will want to use await and therefor must be marked with async.

    I hope this clarifies it.