Skip to content

Instantly share code, notes, and snippets.

@joncardasis
Created September 21, 2021 16:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joncardasis/c5a5af3f80dadf5a54a256b260842eb0 to your computer and use it in GitHub Desktop.
Save joncardasis/c5a5af3f80dadf5a54a256b260842eb0 to your computer and use it in GitHub Desktop.
usePromise React hook with TypeScript. React-ify promise resolutions
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