Blog>
Snippets

Middleware for Performing Validation

Illustrate how to write a middleware that validates action payload before it reaches the reducer, potentially dispatching error actions in Redux 5.0.0.
// Middleware function that validates a specific action payload
const validationMiddleware = store => next => action => {
  if (action.type === 'MY_ACTION_TYPE') {
    // Perform validation logic here
    if (isValidAction(action)) {
      // If action is valid, pass it to the next middleware
      return next(action);
    } else {
      // If action is not valid, dispatch an error action
      return next({ type: 'MY_ACTION_ERROR', error: 'Invalid action payload.' });
    }
  }
  // If action type is not the one to validate, pass it to the next middleware
  return next(action);
};

// Function to check if the action payload is valid
function isValidAction(action) {
  // Add validation logic here
  // Return true if valid, false otherwise
  return true; // Replace this with actual validation
}
This piece of code defines a middleware function `validationMiddleware` for Redux that checks the validity of the payload for a specific action type before it reaches the reducer. If the payload is invalid, an error action is dispatched instead.
// Redux store setup with the validation middleware
import { createStore, applyMiddleware } from 'redux';
import rootReducer from './reducers'; // Import the root reducer

// Apply the middleware during store creation
const store = createStore(
  rootReducer,
  applyMiddleware(validationMiddleware)
);
This is an example of how to apply the `validationMiddleware` to a Redux store during its creation, using `createStore` and `applyMiddleware` from Redux.
/* CSS is not required for the middleware functionality,
   however, if you would like to style the error messages:
*/
.error-message {
  color: red;
  font-weight: bold;
}
This CSS snippet provides styles for displaying error messages with bold text in red color, which can be applied to HTML elements where errors are shown on the UI.
<!-- HTML structure for displaying an error message -->
<div id="error-container" class="error-message" style="display: none;">
  <!-- Error message from the Redux state will be inserted here -->
</div>
This HTML provides a container to display any error messages on the UI. By default, it is hidden and should be shown when there is an error in the action payload validation.