Skip to content

Instantly share code, notes, and snippets.

@ChristianIvicevic
Last active September 23, 2019 14:58
Show Gist options
  • Save ChristianIvicevic/f99cebb9f494d1229d8a6cbf6f510baf to your computer and use it in GitHub Desktop.
Save ChristianIvicevic/f99cebb9f494d1229d8a6cbf6f510baf to your computer and use it in GitHub Desktop.
/* eslint-disable no-console */
import {isEqual, isPlainObject} from 'lodash';
import {useEffect, useRef} from 'react';
type Options = Partial<{
/**
* String prefix used to distinguish multiple groups.
*/
groupName: string;
/**
* Boolean value indicating whether to reduce verbosity in the output by collapsing the changes.
*/
isCollapsed: boolean;
/**
* Boolean value indicating whether to format objects using console.table instead of generic JSON.
*/
isTabulated: boolean;
}>;
export const usePropsObserver = <T extends Record<string, unknown>>(
props: T,
options: Options = {
groupName: 'usePropsObserver',
isCollapsed: true
}
) => {
const {groupName, isCollapsed, isTabulated} = options;
const previousFormat = ['%c prev value', 'color: #9E9E9E; font-weight: bold;'];
const nextFormat = ['%c next value', 'color: #4CAF50; font-weight: bold;'];
const previousValues = useRef(props);
const log = (format: string[], value: unknown) => {
if (isTabulated && isPlainObject(value)) {
console.log(...format);
console.table(value);
} else {
console.log(...format, value);
}
};
useEffect(() => {
const changedValues = Object.entries(props).reduce<Record<string, [unknown, unknown]>>(
(changes, [key, value]) => {
if (!isEqual(previousValues.current[key], value)) {
changes[key] = [previousValues.current[key], value];
}
return changes;
},
{}
);
if (Object.keys(changedValues).length) {
console.group(groupName);
Object.entries(changedValues).forEach(([key, [previous, next]]) => {
if (isCollapsed) {
console.groupCollapsed(key);
} else {
console.group(key);
}
log(previousFormat, previous);
log(nextFormat, next);
console.groupEnd();
});
console.groupEnd();
}
previousValues.current = props;
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment