Blog>
Snippets

Using Redux Middleware for Type Checking

Create a custom middleware that validates action payloads against predefined types or schemas before they reach the reducers to catch type-related errors.
const typeCheckingMiddleware = store => next => action => {
  // Define your type schemas for actions here
  const actionTypeSchemas = {
    'ADD_TODO': {
      text: 'string',
      completed: 'boolean',
    },
    // ...Add more action types and their expected payload schema
  };

  const schema = actionTypeSchemas[action.type];
  if (schema && typeof action.payload !== 'undefined') {
    for (const key of Object.keys(schema)) {
      if (typeof action.payload[key] !== schema[key]) {
        throw new Error(`Invalid type for property ${key}. Expected ${schema[key]}, found ${typeof action.payload[key]}.`);
      }
    }
  }
  return next(action);
};
This is a custom Redux middleware for type checking. It validates the payload of each action against predefined schemas based on the action type before passing the action to the next middleware or the reducer.
import { createStore, applyMiddleware } from 'redux';
import rootReducer from './reducers';

// Apply the middleware to the store
const store = createStore(
  rootReducer,
  applyMiddleware(typeCheckingMiddleware)
);
This snippet shows how to apply the custom typeCheckingMiddleware to the Redux store. It imports the middleware and applies it when creating the store using redux's `applyMiddleware` function.
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Redux Middleware Type Checking Example</title>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/redux/4.0.5/redux.min.js"></script>
</head>
<body>
  <!-- Your HTML content here -->
  <script src="./app.js"></script>
</body>
</html>
This is a basic HTML template including the Redux library via CDN. The JavaScript code where the Redux store and middleware are defined is expected to be in a file named app.js.
/* No additional CSS needed for the Redux Logic */
In this specific example, CSS is not required because we are focused on Redux middleware for type checking; there is no direct visual aspect to style for the middleware logic.