Avoiding Non-Serializable Values in Reducers
Present a code snippet warning against the use of non-serializable values in reducers, such as Dates or Promises, by providing an example of common mistakes and how to refactor them for correct usage with Redux Toolkit.
// Incorrect: Storing non-serializable values directly in the state
const initialState = {
lastUpdated: new Date() // Non-serializable
};
const someReducer = (state = initialState, action) => {
switch (action.type) {
case 'UPDATE_TIMESTAMP':
return {
...state,
lastUpdated: new Date() // Non-serializable
};
default:
return state;
}
};
This code incorrectly adds a non-serializable value (Date object) directly to the Redux state.
// Correct: Storing serializable values in the state
const initialState = {
lastUpdated: Date.now() // Serializable as it's a number
};
const someReducer = (state = initialState, action) => {
switch (action.type) {
case 'UPDATE_TIMESTAMP':
return {
...state,
lastUpdated: Date.now() // Serializable
};
default:
return state;
}
};
This refactored code replaces the Date object with the number of milliseconds since the Unix epoch (Date.now()), which is serializable.