From 76fa37e46638a4bb56e6b5d95cd3d972d3c10760 Mon Sep 17 00:00:00 2001 From: Tsu-ba-me Date: Fri, 9 Sep 2022 22:48:20 -0400 Subject: [PATCH] feat(striker-ui): add hooks to handle async cleanup --- striker-ui/hooks/useProtect.ts | 30 +++++++++++++++++++++++++++ striker-ui/hooks/useProtectedState.ts | 25 ++++++++++++++++++++++ 2 files changed, 55 insertions(+) create mode 100644 striker-ui/hooks/useProtect.ts create mode 100644 striker-ui/hooks/useProtectedState.ts diff --git a/striker-ui/hooks/useProtect.ts b/striker-ui/hooks/useProtect.ts new file mode 100644 index 00000000..660780c0 --- /dev/null +++ b/striker-ui/hooks/useProtect.ts @@ -0,0 +1,30 @@ +import { useEffect, useRef } from 'react'; + +// Allow any function as callback in the protect function. +// Could be used to wrap async callbacks to prevent them from running after +// component unmount. +// eslint-disable-next-line @typescript-eslint/no-explicit-any +type AnyFunction = (...args: any[]) => any; + +type ProtectFunction = ( + fn: F, + ...args: Parameters +) => ReturnType; + +const useProtect = (): { protect: ProtectFunction } => { + const isComponentMountedRef = useRef(true); + + useEffect( + () => () => { + isComponentMountedRef.current = false; + }, + [], + ); + + return { + protect: (fn, ...args) => + isComponentMountedRef.current ? fn(...args) : undefined, + }; +}; + +export default useProtect; diff --git a/striker-ui/hooks/useProtectedState.ts b/striker-ui/hooks/useProtectedState.ts new file mode 100644 index 00000000..019fc9c0 --- /dev/null +++ b/striker-ui/hooks/useProtectedState.ts @@ -0,0 +1,25 @@ +import { Dispatch, SetStateAction, useState } from 'react'; + +type SetStateFunction = Dispatch>; + +type SetStateParameters = Parameters>; + +type SetStateReturnType = ReturnType>; + +const useProtectedState = ( + initialState: S | (() => S), + protect: ( + fn: SetStateFunction, + ...args: SetStateParameters + ) => SetStateReturnType, +): [S, SetStateFunction] => { + const [state, setState] = useState(initialState); + + return [ + state, + (...args: SetStateParameters): SetStateReturnType => + protect(setState, ...args), + ]; +}; + +export default useProtectedState;