Blog>
Snippets

Customizing the serializableStateInvariantMiddleware

Provide an example of how to configure the `serializableStateInvariantMiddleware` to ignore specific non-serializable values like dates or complex classes.
import { configureStore } from '@reduxjs/toolkit';
import { combineReducers } from 'redux';
import { createSerializableStateInvariantMiddleware } from '@reduxjs/toolkit';

const rootReducer = combineReducers({/* your reducers here */});

const isSerializable = (value) => {
    // Implement custom serialization logic here.
    // For example, check if the value is an instance of Date.
    return value instanceof Date || /* other checks for serializability */;
};

const getEntries = (value) => {
    // Retrieve entries of the value for serialization checks.
    // Entries can be key-value pairs of Objects, Maps, etc.
    return Object.entries(value);
};

const serializableMiddleware = createSerializableStateInvariantMiddleware({
    isSerializable,
    getEntries,
});

const store = configureStore({
    reducer: rootReducer,
    middleware: (getDefaultMiddleware) => getDefaultMiddleware().concat(serializableMiddleware),
});

export default store;
This code sets up a Redux store with a custom instantiation of the `serializableStateInvariantMiddleware`. The `isSerializable` function is provided to customize the serialization check. It determines whether a value is considered serializable, for example, by allowing instances of Date to bypass the check. The `getEntries` function is responsible for getting the entries of a given value, to be used by the middleware to check their serializability. The custom middleware is then added to the Redux store's middleware chain.