Blog>
Snippets

Serializing state with Object.create(null) in Redux

Provide an example to demonstrate serialization and deserialization of Redux state objects created with Object.create(null).
const initialState = Object.create(null);
initialState.counter = 0;

// Redux reducer
function counterReducer(state = initialState, action) {
  switch (action.type) {
    case 'INCREMENT':
      return {...state, counter: state.counter + 1};
    default:
      return state;
  }
}
Defines a Redux reducer with an initial state created using Object.create(null). It handles 'INCREMENT' actions.
const serializeState = (state) => JSON.stringify(state);

const deserializeState = (serializedState) => {
  const state = Object.create(null);
  return Object.assign(state, JSON.parse(serializedState));
};
Provides a serializeState function for converting the state to a JSON string and a deserializeState function for converting the JSON string back to a state object with the prototype as null.
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Redux Serialization Example</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/redux/4.0.5/redux.min.js"></script>
    <script>
        // Include the reducer and serialization functions here
    </script>
</head>
<body>
    <button id="increment">Increment</button>
    <script>
        // Redux store creation and event listeners for the button
    </script>
</body>
</html>
HTML structure to include a button that when clicked will trigger incrementing a value in the Redux store. Include the Redux library and script tags for reducer and the serialize/deserialize functions, plus the store creation and handling logic.
const { createStore } = Redux;
const store = createStore(counterReducer);

document.getElementById('increment').addEventListener('click', () => {
  store.dispatch({ type: 'INCREMENT' });
  const currentState = store.getState();
  const serializedState = serializeState(currentState);
  console.log('Serialized State:', serializedState);

  // Simulate saving to and retrieving from localStorage or a server.
  localStorage.setItem('appState', serializedState);
  const storedState = localStorage.getItem('appState');
  const deserializedState = deserializeState(storedState);
  console.log('Deserialized State:', deserializedState);
});
Creates a Redux store with the previously defined reducer, sets up an event listener on the increment button, dispatches actions to the store, and logs the serialized and deserialized state for demonstration purposes.