From bdc69c18c1986544497b6974ffe5d8e073e4be6d Mon Sep 17 00:00:00 2001
From: crupest <crupest@outlook.com>
Date: Thu, 14 Sep 2023 18:58:44 +0800
Subject: ...

---
 .../components/hooks/useAutoUnsubscribePromise.tsx | 23 ++++++++++++++++++++++
 1 file changed, 23 insertions(+)
 create mode 100644 FrontEnd/src/components/hooks/useAutoUnsubscribePromise.tsx

(limited to 'FrontEnd/src/components/hooks/useAutoUnsubscribePromise.tsx')

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);
+}
-- 
cgit v1.2.3

