Skip to content

Instantly share code, notes, and snippets.

@PabloLION
Forked from albertorestifo/propdiff.js
Last active November 26, 2021 20:36
Show Gist options
  • Save PabloLION/88428f51b12ce3836a7f20c8bb00264a to your computer and use it in GitHub Desktop.
Save PabloLION/88428f51b12ce3836a7f20c8bb00264a to your computer and use it in GitHub Desktop.
Logs change with git diff style between current and previous object
// Example usage for React class component.
// Can also it for state or non-react JS.
componentDidUpdate(prevProps) {
logUpdatedDiff(prevProps, this.props)
}
/**
* @param {object} prev: previous to compare
* @param {object} current: current to compare
* @return {void}
*/
function logUpdatedDiff(prev, current) {
const now = Object.entries(current);
const added = now.filter(([key, val]) => {
if (prev[key] === undefined) return true;
if (prev[key] !== val) {
console.log(
`${key}
%c- ${JSON.stringify(prev[key])}
%c+ ${JSON.stringify(val)}`,
"color:red;",
"color:green;"
);
}
return false;
});
added.forEach(([key, val]) =>
console.log(
`${key}
%c+ ${JSON.stringify(val)}`,
"color:green;"
)
);
}
@dmilanp
Copy link

dmilanp commented Nov 26, 2021

Very handy! Thank you

@PabloLION
Copy link
Author

Very handy! Thank you

@dmilanp You are welcome. Although shown on top-left of this page, I still want to point out that this file originated by modifying albertorestifo/propdiff.js, adding some styling and change some order.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment