Enforcing Serializability in Middleware
Provide an example of a custom middleware in Redux v5.0.0 that checks for action serializability and logs a warning if non-serializable values are detected.
const isSerializable = value =>
typeof value !== 'function' && !(value instanceof Error) && !(value instanceof HTMLElement);
const serializabilityMiddleware = store => next => action => {
const keys = Object.keys(action);
keys.forEach(key => {
if (!isSerializable(action[key])) {
console.warn(`Non-serializable value detected in action at key: "${key}".`,
'Take a look at the value: ', action[key],
'Check the logic that dispatched this action: ', action);
}
});
return next(action);
};
// Usage in Redux config
// import { createStore, applyMiddleware } from 'redux';
// const store = createStore(reducer, applyMiddleware(serializabilityMiddleware));
This custom Redux middleware, 'serializabilityMiddleware', checks each key in the action object to ensure that its value is serializable. If a non-serializable value is detected, such as a function or an Error object, it logs a warning to the console indicating the key and the value. Functions for serializability checking and the middleware are both declared. A comment at the end provides an example of how to apply the middleware in the Redux store configuration.