What are middleware in the context of Redux?
Middleware are pieces of code that are executed between the triggering of an action and its arrival at the reducer in Redux. This technique, widely used in backend server management, allows you to perform several essential tasks for application development:
- Error Handling: You can integrate error logs and send them to services such as Sentry.
- Data Fetch: Make requests and manage data efficiently.
- Application Debugging: Helps debug the flow of data in your application.
How does middleware work in Redux?
To understand middleware, it is crucial to remember some key Redux concepts:
- Store Creator: Function that creates the Redux Store.
- Enhancers: Higher-order functions that take a Store Creator and return an enhanced version.
- Compose: Functional programming utility that combines multiple functions in an orderly fashion.
Creating Custom Middleware
The implementation of a custom middleware, called Logger
, is based on curried functions, where each function returns another function:
const logger = store => next => action => { console.log('Dispatching action:', action); return next(action);};
- The first function receives the
store
.
next
is called when the middleware finishes its work and passes the action to the reducer.
action
contains the information of the triggered action.
Integration of the Middleware in our Application
To add a middleware:
-
Import the middleware and Redux:
import { createStore, applyMiddleware, compose } from 'redux';import logger from './middleware/logger';
-
Use applyMiddleware
to integrate it:
const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;const store = createStore( rootReducer, composeEnhancers(applyMiddleware(logger)));
This approach allows you to add various middleware and enhancers, empowering the Store.
Advanced implementation: Manipulating actions with middleware
Modifying actions before they reach the reducer can enrich your application. Imagine we receive data from an API and want to add a custom Pokémon:
Creating Featuring
Middleware
const featuring = store => next => action => { if (action.type === 'FETCH_POKEMON_SUCCESS') { const newPayload = [{ name: 'Eddy' }, ...action.payload]; const updatedAction = {... action, payload: newPayload }; return next(updatedAction); } return next(action);};
Multiple Middleware Application
The applyMiddleware
function accepts multiple middleware:
const store = createStore( rootReducer, composeEnhancers(applyMiddleware(logger, featuring)));
With this practice, we look at how to add and modify data before reaching the reducer, allowing us to customize the user experience.
Challenge for you
I hope these explanations have piqued your interest in middleware. Now I invite you to create your own middleware and share your solution. I look forward to seeing your creativity in action - keep exploring and learning! I'll be waiting for you in the next class to discover how to use third-party libraries as middleware in your project.
Want to see more contributions, questions and answers from the community?