Blog>
Snippets

Updating Custom Middleware for Redux v5.0.0

Revise a custom middleware function to be compatible with the middleware API changes in Redux v5.0.0.
// Define a very simple logger middleware
const loggerMiddleware = storeAPI => next => action => {
  console.log('dispatching', action)
  let result = next(action)
  console.log('next state', storeAPI.getState())
  return result
}

// Create Redux store with that middleware
const store = Redux.createStore(
  rootReducer,
  Redux.applyMiddleware(loggerMiddleware)
)

// Dispatch an action to test the logger middleware
store.dispatch({ type: 'TEST_ACTION' })
This JavaScript code defines a simple custom logger middleware compatible with Redux v5.0.0. The loggerMiddleware function takes the storeAPI object, and returns a function taking the next middleware's dispatch method, which returns another function taking the action to be dispatched. When an action is dispatched, it logs the action and the new state after the action is processed. The Redux.createStore is used to create the Redux store with the logger middleware applied using Redux.applyMiddleware.
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Redux Middleware Update Example</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/redux/5.0.0/redux.min.js"></script>
</head>
<body>
    <div id="app"></div>
    <script src="app.js"></script>
</body>
</html>
This is an HTML document that sets up a basic page with Redux v5.0.0 included. The script tag with `src="app.js"` would link to an external JavaScript file where the Redux store is created, and middleware is applied. This particular code does not implement any middleware logic; it just includes the Redux library from a CDN and sets up the page structure.
body {
  font-family: Arial, sans-serif;
}

#app {
  padding: 20px;
  background-color: #f7f7f7;
  border-radius: 8px;
  max-width: 600px;
  margin: auto;
}
This is a CSS snippet giving basic styles to the body of the document and the #app div element where the Redux application would be rendered. It defines the font family, applies padding, sets a background color, and also styles it with a border-radius, maximum width, and centered alignment.