The quotes() function implements a standard reducer by handling the three synchronous actions and generating the new application state accordingly. The status property is not strictly required for the correct behavior of the application, but it may be useful in order to give feedback to the user. The structure of the application state consists of a data array, containing the list of quotes to show (in our case, we will have just one quote), and a status string, representing the current status of the asynchronous action. The markup of the webpage appears as follows: įor the JavaScript side, you need to get the redux and redux-thunk dependencies and import a few items in the module, as shown below: import ) Let’s put these concepts into practice by implementing a simple application that shows a random Ron Swanson quote from a specialized API. Unlike the reducer, middleware is not required to be a pure function, so the Thunk middleware can perform functions that trigger side effects without any problems. In order to solve our problem with asynchronous tasks, we can define an action as a function that starts an asynchronous task and delegates its execution to the Thunk middleware. This simple behavior allows us to create actions not as simple objects, but as functions that have business logic. The role of this middleware is very simple: verify if an action is a function and, if it is, execute it. ![]() The first approach is based on the Thunk middleware. Using Thunk and Redux Toolkit to manage asynchronous actions In fact, by its nature, the result of an asynchronous task is based on a side effect.So, let’s take a look at a couple of valid solutions to this problem. However, this implementation violates the constraint that a reducer must be a pure function. That said, you may be tempted to support asynchronous actions by modifying their reducers, i.e., making sure that the reducer intercepting that action starts the asynchronous task and manages its outcome. When the asynchronous task ends, a callback should manage the outcome of the asynchronous task and appropriately update the state with either a positive or negative response. Implementing this approach requires that you dispatch the action that starts the asynchronous task. ![]() The common approach to integrating asynchronous tasks into the Redux architecture is to break an asynchronous action into at least three synchronous actions, each informing that the asynchronous task:Įach of these actions changes the application state and keeps it in line with what is happening during the asynchronous task execution. This should give you a good idea about how middleware works with Redux.
0 Comments
Leave a Reply. |