Blog>
Snippets

Implementing Middleware with TypeScript in Redux v5.0.0

Provide an example of creating strongly-typed middleware using TypeScript for Redux v5.0.0.
import { Middleware, Dispatch, AnyAction } from 'redux';

interface MyState {
  // Define your state interface here
}

// Typed middleware
const myMiddleware: Middleware<{}, MyState> = store => next => action => {
  console.log('Middleware triggered:', action);
  // Perform middleware tasks here

  // Call the next dispatch method in the middleware chain.
  return next(action);
};

export default myMiddleware;
This TypeScript code defines a strongly-typed middleware function for Redux. The 'myMiddleware' variable is declared with the Middleware type, which is parameterized with an empty object for the dispatch generic and 'MyState' for the state generic. The middleware function logs the action to the console and then passes control to the next middleware in the chain.
import { createStore, applyMiddleware } from 'redux';
import myMiddleware from './myMiddleware'; // Import the middleware from the previous snippet
import rootReducer from './reducers'; // Import your combined reducers

// Apply middleware to the store
const store = createStore(
  rootReducer,
  applyMiddleware(myMiddleware)
);

export default store;
This code snippet shows how to apply the custom middleware to a Redux store. It imports the 'createStore' and 'applyMiddleware' functions from the 'redux' package, as well as the 'myMiddleware' defined in the previous code snippet. The 'rootReducer' is a combination of different reducers, which is not shown here. The createStore function is then used to create the Redux store, applying the 'myMiddleware' using 'applyMiddleware'.
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Redux Middleware Example</title>
</head>
<body>
  <div id="app"></div>
  <!-- Import your compiled JavaScript bundle containing the Redux store and middleware -->
  <script src="path_to_your_bundle.js"></script>
</body>
</html>
This HTML markup sets up a basic page structure. It includes a 'div' element with the id 'app' where the application's UI would be mounted. At the bottom of the body, a script tag is added to include a JavaScript bundle that contains the Redux store and the middleware. The actual path to the JavaScript bundle will vary based on the bundler and project setup.
body {
  font-family: Arial, sans-serif;
}
This CSS snippet would affect the 'body' element of the HTML markup, setting the font to Arial with a fallback to the default sans-serif font stack.