⊗jsrxPmATCATA 46 of 57 menu

Benefits of using createAsyncThunk in Redux

In the last lesson, we used the createAsyncThunk function from RTK to write our first thunk. In this lesson I'd like to talk a little about the usefulness of this function when sending requests.

In general, the logic for getting data using the fetch method in Redux looks quite boilerplate. And, accordingly, to send the request status to the thunk, we need to create at least three actions (with type and payload). The first should be sent when sending the request, the second - when the request is successful, and the third - when it is unsuccessful. Then they can be sent using dispatch in the thunk code, for example, in try-catch blocks. As a result, such code can look quite cumbersome and inconvenient (just look at the documentation). Each of the actions can have its own action creator. In addition, the sequence of their sending and the actions themselves in particular cannot be confused. Of course, this is not necessarily the case, but it is a common practice when submitting requests.

Luckily, we don't have to do all this manually anymore - now the createAsyncThunk function will do it and generate a thunk that will dispatch all these actions automatically. We just need to pass a callback to createAsyncThunk that will make an asynchronous call and return a promise with the result. That's what we did in the last lesson.

enru