All files / src/hooks/common/data-management useLogs.ts

100% Statements 14/14
100% Branches 0/0
100% Functions 6/6
100% Lines 14/14

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42          4x 612x   612x 11x 11x           612x 9x 9x     612x 10x     612x 306x 36x       612x                    
import { isEqual } from "lodash";
import { useRef } from "react";
 
type TData<T> = Record<string, T>;
 
const useLogs = <T>() => {
  const changeLog = useRef<TData<T>>({});
 
  const updateChangeLogItem = (key: string, value: T) => {
    const currentLogs = changeLog.current;
    changeLog.current = {
      ...currentLogs,
      [key]: value,
    };
  };
 
  const updateChangeLog = (callback: (old: TData<T>) => TData<T>) => {
    const newData = callback(changeLog.current);
    changeLog.current = newData;
  };
 
  const resetChangeLog = () => {
    changeLog.current = {};
  };
 
  const hasChanged = (initialData: TData<T>) => {
    return Object.keys(changeLog.current).some(
      (key) => !isEqual(initialData[key], changeLog.current[key]),
    );
  };
 
  return {
    logs: changeLog.current,
    updateItem: updateChangeLogItem,
    updateAll: updateChangeLog,
    reset: resetChangeLog,
    hasChanged,
  };
};
 
export default useLogs;