aboutsummaryrefslogtreecommitdiff
path: root/FrontEnd/src/components/hooks/useAutoUnsubscribePromise.tsx
blob: 78e21151225f5282cae58cfc6269c95c8a6311a4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
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);
}