Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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