-
Notifications
You must be signed in to change notification settings - Fork 3
/
useConfirm.tsx
44 lines (34 loc) · 1.17 KB
/
useConfirm.tsx
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
import { useCallback, useContext, useEffect, useMemo } from "react";
import ConfirmContext from "./ConfirmContext";
import { ConfirmationDialogOptions } from "./ConfirmProvider.types"; // Ensure this type exists in your types file
let idCounter = 0;
// generate a unique id for each confirmation dialog
const useConfirmId = (): string => {
const id = useMemo(() => {
return idCounter++;
}, []);
return `confirm-${id}`;
};
// define the type for the confirm function options
interface UseConfirm {
(options: Partial<ConfirmationDialogOptions>): Promise<void>;
}
const useConfirm = (): UseConfirm => {
const parentId = useConfirmId();
const { confirmBase, closeOnParentUnmount } = useContext(ConfirmContext);
// confirm function uses the context's confirmBase
const confirm = useCallback(
(options: Partial<ConfirmationDialogOptions>) => {
return confirmBase(parentId, options);
},
[parentId, confirmBase]
);
// clean up by calling closeOnParentUnmount when component unmounts
useEffect(() => {
return () => {
closeOnParentUnmount(parentId);
};
}, [parentId, closeOnParentUnmount]);
return confirm;
};
export default useConfirm;