Search code examples
reactjsredux-thunkredux-toolkit

Is dispatch function returned from useDispatch hook synchronous with async thunk?


Async thunk:

const getMovies = createAsyncThunk('recommended/getMovies', async () =>{
    const result = await api.getRecommendedMovies();
    console.log('first')
    return result;
});

Function that uses dispatch function from useDispatch hook:

const getMovies = (page) => {console.log(moviesData)
    const moviesData = dispatch(recommendedMoviesActions.getMovies());
    console.log('second');
};

The console logs are as follows:

  1. 'second'
  2. 'first'

Why did this result like that? Shouldn't it be 1. 'first, 2. 'second' because dispatching is synchronous?


Solution

  • createAsyncThunk returns a standard Redux thunk action creator. You return a promise from the thunk(async/await), dispatch(recommendedMoviesActions.getMovies()) returns a promise, so you should wait for the promise to resolve before doing additional work. See Unwrapping Result Actions

    import { configureStore, createAsyncThunk } from '@reduxjs/toolkit';
    
    const api = {
      getRecommendedMovies: () => Promise.resolve(),
    };
    
    const getMovies = createAsyncThunk('recommended/getMovies', async () => {
      const result = await api.getRecommendedMovies();
      console.log('first');
      return result;
    });
    
    const store = configureStore({ reducer() {} });
    // second, first
    // store.dispatch(getMovies());
    // console.log('second');
    
    // first, second
    store.dispatch(getMovies()).then(() => {
      console.log('second');
    });