Skip to content

Instantly share code, notes, and snippets.

@sethlivingston
Created July 14, 2021 21:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sethlivingston/88e07d0499d27ef4136392867adfc3a8 to your computer and use it in GitHub Desktop.
Save sethlivingston/88e07d0499d27ef4136392867adfc3a8 to your computer and use it in GitHub Desktop.
Logs a reducer that uses Immer
import { Reducer } from "react";
import { current } from "immer";
import { diff } from "helpers/diff"; // See my "Object diff" gist
const quickPayloadTypes = ["boolean", "number", "string"];
export function logImmerReducer(reducer: Reducer<any, any>): Reducer<any, any> {
if (process?.env?.JEST_WORKER_ID) return reducer;
return function (state: any, action: any): any {
const isQuickType = quickPayloadTypes.includes(typeof action.payload);
if (isQuickType) {
console.groupCollapsed(`dispatch: ${action.type}: ${action.payload}`);
} else {
console.groupCollapsed(`dispatch: ${action.type}`);
if (action.payload !== undefined) {
console.log(` payload:`, action.payload);
}
}
const prevState = current(state);
const nextState = reducer(state, action);
console.log(` delta:`, diff(prevState, current(state), true));
console.groupEnd();
return nextState;
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment