Redux has now become an integral part of the web app development, especially when developed with React. It offers so much flexibility and scalability that no other library as of now. With good coding practices, it is now very feasible to use redux even for small projects and for incremental projects it really leads the way.
Redux is not just only about the store, actions and reducers, it is much more powerful, robust and scalable when middlewares are used. Conventionally, the middlewares come under the advanced redux but I think middlewares are also a very important part of the redux architecture.
What is a Redux Middleware?
A redux middleware is nothing more than a function which is invoked on every action and we can do almost anything e.g Data manipulations, popups, confirmations, API response validation and more, before pushing the updates to the reducers followed by the state change.
Advantages
Disadvantages
How to write your own middleware?
Writing middlewares is as simple as writing simple functions and all you need to do is wrap the middlewares in your redux store using applyMiddleware method.
What are we going to make?
We are going to make an API middleware which will process our API requests and send the API response (success/error) and other data (isLoading / isLoaded). With this we won’t have to worry about writing the same code again and again, like retrieving the response data or setting/resetting the loading. Also, one of the biggest advantage is we can dispatch multiple actions inside our middleware when needed.
Let’s Get Started
OR
Where store = Redux store, next = Dispatch function, action = Action fired by the user
You can see here, we have modified the type to types in order to dispatch multiple actions. E.g Firing loading actions to set/reset isLoading before and after the API request.
You can use the redux dev extension to know about the changes and actions fired. In this way you will be able to check state diffs on each action.
Code Repository - https://github.com/vishalchandna1/react-example/tree/redux-middleware
Summary
We have implemented an API middleware function which is fired on all the action and filters out the API actions. A number of actions are fired e.g setting/resetting the loading before and after the API is requested and the final response is received. The code might confuse you a bit but try to understand the big picture here. With middlewares, we wouldn’t have to worry about handling the same stuff repeatedly.