Created
July 14, 2021 21:18
-
-
Save sethlivingston/88e07d0499d27ef4136392867adfc3a8 to your computer and use it in GitHub Desktop.
Logs a reducer that uses Immer
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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