aboutsummaryrefslogtreecommitdiff
path: root/FrontEnd/src/components/hooks/useAutoUnsubscribePromise.ts
blob: 01c5a1db35aabdb0178d9aa507d60f1a5195f309 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
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;
      };
    }
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [promiseGenerator, resultHandler, ...(dependencies ?? [])]);
}