You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
30 lines
762 B
30 lines
762 B
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 = <F extends AnyFunction>( |
|
fn: F, |
|
...args: Parameters<F> |
|
) => ReturnType<F>; |
|
|
|
const useProtect = (): { protect: ProtectFunction } => { |
|
const isComponentMountedRef = useRef<boolean>(true); |
|
|
|
useEffect( |
|
() => () => { |
|
isComponentMountedRef.current = false; |
|
}, |
|
[], |
|
); |
|
|
|
return { |
|
protect: (fn, ...args) => |
|
isComponentMountedRef.current ? fn(...args) : undefined, |
|
}; |
|
}; |
|
|
|
export default useProtect;
|
|
|