React: Redux Toolkit
Theory: Asynchronous requests via Thunk
One of the most complicated tasks in building front-end applications is dealing with external requests. Difficulties come from two sides.
On the one hand, asynchrony itself generates ambiguities, so the standard mechanisms stop working. Redux doesn't know how to work asynchronously, so all the processing of requests takes place outside Redux. In this case, any non-trivial logic for processing asynchronous actions will appear inside React components:
On the other hand, the network is an unreliable thing. Requests can take a long time or fail, so we should monitor them to ensure we get the correct response. If the request takes a long time, we show a spinner. If the request is interrupted, we display the corresponding warning:
We write a lot of similar code, even for a few calls. In real applications, the number of calls could be dozens or hundreds. Therefore, you can't do without a ready-made solution. To automate HTTP requests, we need two mechanisms:
- The redux-thunk middleware, already included in Redux Toolkit
- The
createAsyncThunk()mechanism
The redux-thunk middleware allows asynchronous code within dispatch(). That way, we can bring the logic of queries and storage updates into separate functions called thunks:
You can do roughly the same thing without redux-thunk just by writing an asynchronous function to which we pass dispatch() as input. The difference shows up in the more advanced use cases. For example, when we work with state or global objects, such as a WebSocket connection. In this case, you have to use redux-thunk, which makes this all much easier to do:
Despite the convenience gained, thunks do not reduce the amount of code, and the same error handling will make up a large part of the code. This is where createAsyncThunk():
Each thunk created with createAsyncThunk() contains three reducers: pending, fulfilled, and rejected. They correspond to promise states and are called by Redux Toolkit the moment the promise enters one of these states. We don't have to respond to all, so we can choose what is important to us in the application.
Recommended programs
Completed
0 / 7


