Created
September 21, 2021 16:33
-
-
Save joncardasis/c5a5af3f80dadf5a54a256b260842eb0 to your computer and use it in GitHub Desktop.
usePromise React hook with TypeScript. React-ify promise resolutions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useCallback, useState, useRef, useEffect } from 'react'; | |
const usePromise = <T, U extends any[]>(operation: (...args: U) => Promise<T>) => { | |
const [data, setData] = useState<T>(); | |
const [error, setError] = useState<Error>(); | |
const [loading, setLoading] = useState(false); | |
const mounted = useRef<boolean>(true); | |
useEffect( | |
() => () => { | |
mounted.current = false; | |
}, | |
[], | |
); | |
const invoke = useCallback( | |
(...args: U) => { | |
setLoading(true); | |
operation(...args) | |
.then((res) => { | |
if (mounted.current) { | |
setError(undefined); | |
setData(res); | |
} | |
}) | |
.catch((err) => mounted.current && setError(err)) | |
.finally(() => mounted.current && setLoading(false)); | |
}, | |
[operation], | |
); | |
const _reset = useCallback(() => { | |
setData(undefined); | |
setError(undefined); | |
setLoading(false); | |
}, []); | |
return [invoke, { data, loading, error, _reset }] as const; | |
}; | |
export default usePromise; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment