diff options
| author | Oskar Nyberg <oskar@mullvad.net> | 2021-02-16 16:44:37 +0100 |
|---|---|---|
| committer | Oskar Nyberg <oskar@mullvad.net> | 2021-07-02 16:15:01 +0200 |
| commit | 694ad87692c378a621c7c4a669c0ff88ca78d633 (patch) | |
| tree | 8663112bcdc5e1a02bbd0ed10f376197c07be18e /gui/src | |
| parent | eef48516140073514d86ce97ffd5a7b042b66b0d (diff) | |
| download | mullvadvpn-694ad87692c378a621c7c4a669c0ff88ca78d633.tar.xz mullvadvpn-694ad87692c378a621c7c4a669c0ff88ca78d633.zip | |
Add useAsyncEffect hook
Diffstat (limited to 'gui/src')
| -rw-r--r-- | gui/src/renderer/lib/utilityHooks.ts | 21 |
1 files changed, 21 insertions, 0 deletions
diff --git a/gui/src/renderer/lib/utilityHooks.ts b/gui/src/renderer/lib/utilityHooks.ts index ee3f191593..9e8cea0bad 100644 --- a/gui/src/renderer/lib/utilityHooks.ts +++ b/gui/src/renderer/lib/utilityHooks.ts @@ -1,4 +1,5 @@ import React, { useCallback, useEffect, useRef } from 'react'; +import consumePromise from '../../shared/promise'; export function useMounted() { const mountedRef = useRef(false); @@ -25,3 +26,23 @@ export function assignToRef<T>(element: T | null, ref?: React.Ref<T>) { (ref as React.MutableRefObject<T>).current = element; } } + +export function useAsyncEffect( + effect: () => Promise<void | (() => void | Promise<void>)>, + dependencies: unknown[], +): void { + const isMounted = useMounted(); + + useEffect(() => { + const promise = effect(); + return () => { + consumePromise( + promise.then((destructor) => { + if (isMounted() && destructor) { + return destructor(); + } + }), + ); + }; + }, dependencies); +} |
