Blog>
Snippets

Middleware for State Diffing

Create middleware for Redux that compares the previous and next state, calculates the differences, and dispatches only the changes to be synchronized across devices.
import { isEqual } from 'lodash';
import { diff } from 'deep-diff';

const stateDiffMiddleware = ({ getState, dispatch }) => next => action => {
  // Get the current state before the action is dispatched
  const prevState = getState();
  // Dispatch the action
  const returnValue = next(action);
  // Get the next state after the action is dispatched
  const nextState = getState();
  // Calculate the differences
  const differences = diff(prevState, nextState);

  // If there are differences, dispatch an action with those differences
  if(differences) {
    dispatch({ type: 'STATE_DIFFS', payload: differences });
  }

  return returnValue;
};

export default stateDiffMiddleware;
This middleware uses Lodash's isEqual and deep-diff's diff functions to compare previous and next states. If there are differences, it dispatches an action with the type 'STATE_DIFFS' containing the differences payload, which can then be used to synchronize state across devices.