All files / src/components/common/Error ResetActionContext.tsx

85.71% Statements 12/14
25% Branches 1/4
80% Functions 4/5
91.66% Lines 11/12

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 43 44 45 46              202x           202x 293x       293x 7x           293x   293x                 202x 775x   775x       775x    
import React, { createContext, useContext, useState } from "react";
 
interface ResetActionContextProps {
  registerResetAction: (id: string, action: () => void) => void;
  getResetAction: (id: string) => (() => void) | null;
}
 
const ResetActionContext = createContext<ResetActionContextProps | undefined>(
  undefined,
);
 
export const ResetActionProvider: React.FunctionComponent<{
  children: React.ReactNode;
}> = ({ children }) => {
  const [resetActions, setResetActions] = useState<{
    [id: string]: () => void;
  }>({});
 
  const registerResetAction = (id: string, action: () => void) => {
    setResetActions((prevActions) => ({
      ...prevActions,
      [id]: action,
    }));
  };
 
  const getResetAction = (id: string) => resetActions[id] || null;
 
  return (
    <ResetActionContext.Provider
      value={{ registerResetAction, getResetAction }}
    >
      {children}
    </ResetActionContext.Provider>
  );
};
 
export const useResetAction = (): ResetActionContextProps => {
  const context = useContext(ResetActionContext);
 
  Iif (!context) {
    throw new Error("useResetAction must be used within a ResetActionProvider");
  }
 
  return context;
};