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

92.3% Statements 12/13
50% Branches 2/4
100% Functions 5/5
100% Lines 11/11

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          4x 306x   306x 8x   306x 11x 11x   11x 11x           306x   306x                  
import { isFunction } from "lodash";
import { useState } from "react";
 
type TData<T> = Record<string, T>;
 
const useHashedData = <T>() => {
  const [data, setData] = useState<TData<T> | undefined>(undefined);
 
  const updateAll = (callback: (oldData?: TData<T>) => TData<T>) =>
    setData(callback);
 
  const updateEntry = (key: string, newValue: ((prevItem: T) => T) | T) =>
    setData((prev) => {
      Iif (!prev) return prev;
 
      const updatedItem = isFunction(newValue) ? newValue(prev[key]) : newValue;
      return {
        ...data,
        [key]: updatedItem,
      };
    });
 
  const reset = (newData?: TData<T>) => setData(newData);
 
  return {
    data,
    updateAll,
    updateEntry,
    reset,
  };
};
 
export default useHashedData;