Created
April 13, 2022 15:20
-
-
Save david-arteaga/dd22249bea62a8389639877a67cd43b0 to your computer and use it in GitHub Desktop.
[useLogKeyDifferences] #react #debugging
This file contains hidden or 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 { useRef } from 'react'; | |
export default function useLogKeyDifferences<Type>(object: Type) { | |
const objectRef = useRef<undefined | Type>(undefined); | |
const previousObject = objectRef.current; | |
objectRef.current = object; | |
const differentKeys = new Set<keyof Type>(); | |
(Object.keys(object) as (keyof Type)[]).forEach((key) => { | |
const prev = previousObject?.[key]; | |
const current = object[key]; | |
if (prev !== current) { | |
differentKeys.add(key); | |
} | |
}); | |
(Object.keys(previousObject ?? {}) as (keyof Type)[]).forEach((key) => { | |
const prev = previousObject?.[key]; | |
const current = object[key]; | |
if (prev !== current) { | |
differentKeys.add(key); | |
} | |
}); | |
differentKeys.forEach((key) => { | |
console.log('KeyDifference::', key, ({ | |
previous: previousObject?.[key], | |
current: object[key], | |
})); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment