Search code examples
reduxredux-thunkredux-toolkit

Redux CreateAsyncThunk fetching data


I'm currently exploring the new Redux Toolkit setup. However, I stumbled upon CreateAsyncThunk when fetching data, but I cannot find pros and cons using this over a normal service class using e.g. axios.

Can someone explain to me why I should/shouldn't use the CreateAsyncThunk to fetch data from an api?


Solution

  • Redux is the place where you store your data.

    So after your request you need to dispatch an action, to get your data into Redux.

    Now, often your components are also interested in the question if you already are running a request.

    That information could be stored in your component, but then other components won't know. So you store it in Redux, too.

    Now you need to also dispatch an action to signal Redux that you started loading data.

    The same goes for errors. You need to dispatch an action to signal Redux that loading failed.

    createAsyncThunk takes code from you and executes that. But before, it dispatches an action. And depending if your code was a succcess or had an exception, it also dispatches either a "fulfilled" or "rejected" action for you.

    So you only have to concentrate on the code you want to write.

    So nothing stops you from doing

    const myThunk = createAsyncThunk('myThunk', myApiService.getSomeData)
    

    in the end - which would be using your api service, coupled with createAsyncThunk for the lifecycle actions - assuming your api service only takes one argument, otherwise it'd be

    const myThunk = createAsyncThunk('myThunk', ({name, password}) => myApiService.getSomeData(name, password))
    

    since cAT only forwards one argument from the action creator call.