Skip to content

Instantly share code, notes, and snippets.

@mattmccray
Created June 5, 2021 22:42
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 mattmccray/d73596c4015fce5f425357e0a896a32c to your computer and use it in GitHub Desktop.
Save mattmccray/d73596c4015fce5f425357e0a896a32c to your computer and use it in GitHub Desktop.
import { useEffect, useRef, useState } from "preact/hooks"; // Or 'react'
interface PromiseResult<T> {
isResolved: boolean
value?: T
error?: any
}
export function usePromise<T>(builder: (...params: any[]) => Promise<T>, params: any[] = []): PromiseResult<T> {
const [returnObj, updateReturnObj] = useState({ isResolved: false } as PromiseResult<T>);
const mounted = useRef(true)
useEffect(() => () => {
mounted.current = false
}, [])
useEffect(() => {
async function runPromise() {
try {
updateReturnObj({ isResolved: false });
const value = await builder(...params);
if (mounted.current == false) return
updateReturnObj({ isResolved: true, value });
}
catch (err) {
if (mounted.current == false) return
updateReturnObj({ isResolved: true, error: err });
}
}
runPromise();
}, params);
return returnObj;
}
export default usePromise
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment