Skip to content

Instantly share code, notes, and snippets.

@bkeys818
Created January 13, 2024 17:41
Show Gist options
  • Save bkeys818/f4d9fe9b61c9873f1229ead2f7c3f369 to your computer and use it in GitHub Desktop.
Save bkeys818/f4d9fe9b61c9873f1229ead2f7c3f369 to your computer and use it in GitHub Desktop.
A method that will write a will log any updates to a React state value. This is epecially usefull for tracking changes of the actual value, not the memory location.
import { useRef } from "react";
import { appendFileSync } from "fs";
import { resolve } from "path";
const logFilePath = resolve(__dirname, "./stateUpdates.log");
export function logUpdates(name: string, value: any) {
const ref = useRef();
value = mapObjects(value, simplifyObject);
if (!isEqualValue(ref.current, value)) {
const method = ref.current === undefined && value !== undefined ? "create" : "update";
writeToLogFile(`${name} (${method}): ${format(value)}`);
ref.current = value;
}
}
function writeToLogFile(logEntry: string) {
const formattedLogEntry = `[${new Date().toISOString()}] ${logEntry}\n`;
appendFileSync(logFilePath, formattedLogEntry, "utf-8");
}
function simplifyObject(obj: ObjectLiteral) {
if ("id" in obj) return { id: obj.id };
let key: keyof typeof obj;
for (key in obj) obj[key] = mapObjects(obj[key], simplifyObject);
return obj;
}
/** Calls a defined callback function on every object, allowing you to make them easier to read. */
function mapObjects(value: unknown, callbackfn: (obj: ObjectLiteral) => ObjectLiteral): any {
if (isObject(value)) {
if (Array.isArray(value)) return value.map((v) => mapObjects(v, callbackfn));
else return callbackfn(value);
}
return value;
}
function format(value: unknown): string {
if (value === undefined || value === null) return `${value}`;
if (isObject(value)) {
let json: string;
if (Array.isArray(value)) {
json = `[ ${value.map(format).join(", ")} ]`;
if (value.length < 4 && value.every((v) => !isObject(v))) return json;
} else {
const entries = Object.entries(value);
json = `{ ${entries.map(([key, value]) => `"${key}": ${format(value)}`).join(", ")} }`;
if (entries.length < 4 && entries.every(([_, v]) => !isObject(v))) return json;
}
return JSON.stringify(value, null, 2);
}
return JSON.stringify(value);
}
type ObjectLiteral = Record<string | number | symbol, unknown>;
function isObject(value: unknown): value is ObjectLiteral | unknown[] {
return typeof value == "object" && value !== null;
}
function isEqualValue(a: any, b: any) {
return JSON.stringify(a) === JSON.stringify(b);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment