Blog>
Snippets

Implementing New Serializability Checks in Reducers

Showcase how to update reducers to pass the new state serializability checks implemented in Redux v5.0.0.
// Define a reducer function with appropriate serialization
const myReducer = (state = initialState, action) => {
  switch (action.type) {
    case 'ADD_DATE':
      // Instead of storing Date objects, which are not serializable,
      // Store the date as a string
      return {
        ...state,
        lastUpdated: action.payload.toString(),
      };
    case 'SET_USER':
      // Ensure complex objects like Map are converted to a serializable form
      const userMap = action.payload;
      const serializableUserMap = Object.fromEntries(userMap);
      return {
        ...state,
        userMap: serializableUserMap,
      };
    // other cases... 
    default:
      return state;
  }
};
This reducer function is updated to ensure that non-serializable values (like Date objects and Map) are converted into serializable forms (like strings and plain objects) to pass the Redux v5.0.0 serializability checks.
/* Redux store configuration with the new serializableStateInvariantMiddleware */
import { configureStore } from '@reduxjs/toolkit';
import { serializableStateInvariantMiddleware } from '@reduxjs/toolkit/dist/serializableStateInvariantMiddleware';
import myReducer from './reducers/myReducer';

const store = configureStore({
  reducer: {
    myKey: myReducer,
  },
  middleware: (getDefaultMiddleware) => getDefaultMiddleware({
    serializableCheck: {
      // Pass the new serializability checks
      isSerializable: (value) => typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean' || value === null || typeof value === 'undefined' || Object.prototype.toString.call(value) === '[object Object]',
    },
  }),
});
The Redux store is configured with the new serializableStateInvariantMiddleware to enable serializability checks. The `isSerializable` function is redefined to pass values that are serializable.