CreateSlice serializability enforcement – missing constraint
0 reputation · 09 Aug 2024, 23:19 UTC
0 reputation · 09 Aug 2024, 23:19 UTC
When building a Redux Toolkit store, the createSlice API accepts any JavaScript value as initialState and reducer logic, yet it does not automatically verify that those values are serializable. This omission can lead to silent failures in dev‑tools logging, persistence layers, and production builds where the optional serializableCheck middleware is disabled.
The goal is to guarantee that a slice’s state remains fully serializable, preventing subtle bugs that arise when non‑serializable objects (e.g., Date, Map, Set) are stored. The constraints are: 1) the slice definition itself should expose a clear contract about value serializability; 2) any violation should be reported or blocked at the slice level, not merely at middleware runtime; 3) the solution must remain compatible with existing Redux Toolkit tooling.
What is currently unclear is whether createSlice can be extended to enforce this contract, and how such enforcement would interact with dev‑tools, persistence (e.g., redux‑persist), and production builds that omit the serializability middleware.
createSlice provide a built‑in mechanism to reject non‑serializable state values?33775 reputation · 10 Aug 2024, 00:19 UTC
createSlice does not validate that the initialState or reducer returns are serializable; it treats serializability as a developer responsibility.
import { createSlice, isSerializable } from '@reduxjs/toolkit';
function serializableSlice(options) {
if (!isSerializable(options.initialState)) {
throw new Error('Slice initialState must be serializable');
}
const wrappedReducers = {};
for (const [key, reducer] of Object.entries(options.reducers || {})) {
wrappedReducers[key] = function(state, action) {
const next = reducer(state, action);
if (!isSerializable(next)) {
throw new Error(`Reducer ${key} returned a non‑serializable value`);
}
return next;
};
}
return createSlice({ ...options, reducers: wrappedReducers });
}
If you are already using a persistence library, verify whether it performs its own serialization check; otherwise adopt the wrapper above to catch issues early.
Use comments to ask for clarification. Post a solution as an answer.
No question comments on this page.