Last active
December 6, 2024 11:20
-
-
Save marvinhagemeister/ca36127b2af7236e5334e5969cefa358 to your computer and use it in GitHub Desktop.
preact use hook
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
function use<T>(promiseOrContext: Promise<T> | Context<T>): T { | |
if ('__c' in promiseOrContext) { | |
return useContext(promiseOrContext) | |
} | |
return usePromise(promiseOrContext) | |
} | |
function usePromise<T>(promise: Promise<T>): T { | |
const resolving = useRef(false); | |
const pending = useRef(promise); | |
const unmounted = useRef(false); | |
const [value, setValue] = useState(null); | |
const [error, setError] = useState(null); | |
if (error !== null) { | |
throw error; | |
} | |
if (!resolving.current) { | |
resolving.current = true; | |
pending.current.then( | |
(value) => { | |
if (unmounted.current) return; | |
setValue(value); | |
}, | |
(err) => { | |
if (unmounted.current) return; | |
setError(err); | |
} | |
); | |
} | |
useEffect(() => { | |
return () => { | |
unmounted.current = true; | |
}; | |
}, []); | |
if (!resolved.current) { | |
throw pending.current; | |
} | |
return value; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment