diff options
Diffstat (limited to 'FrontEnd/src/components/hooks')
-rw-r--r-- | FrontEnd/src/components/hooks/index.ts | 1 | ||||
-rw-r--r-- | FrontEnd/src/components/hooks/useAutoUnsubscribePromise.tsx | 23 |
2 files changed, 24 insertions, 0 deletions
diff --git a/FrontEnd/src/components/hooks/index.ts b/FrontEnd/src/components/hooks/index.ts index 771b0e2a..98ce729e 100644 --- a/FrontEnd/src/components/hooks/index.ts +++ b/FrontEnd/src/components/hooks/index.ts @@ -2,3 +2,4 @@ export { useMobile } from "./responsive"; export { default as useClickOutside } from "./useClickOutside"; export { default as useScrollToBottom } from "./useScrollToBottom"; export { default as useWindowLeave } from "./useWindowLeave"; +export { default as useAutoUnsubscribePromise } from "./useAutoUnsubscribePromise"; diff --git a/FrontEnd/src/components/hooks/useAutoUnsubscribePromise.tsx b/FrontEnd/src/components/hooks/useAutoUnsubscribePromise.tsx new file mode 100644 index 00000000..78e21151 --- /dev/null +++ b/FrontEnd/src/components/hooks/useAutoUnsubscribePromise.tsx @@ -0,0 +1,23 @@ +import { useEffect, DependencyList } from "react"; + +export default function useAutoUnsubscribePromise<T>( + promiseGenerator: () => Promise<T> | null | undefined, + resultHandler: (data: T) => void, + dependencies?: DependencyList | undefined, +) { + useEffect(() => { + let subscribe = true; + const promise = promiseGenerator(); + if (promise) { + void promise.then((data) => { + if (subscribe) { + resultHandler(data); + } + }); + + return () => { + subscribe = false; + }; + } + }, dependencies); +} |