Skip to content

Instantly share code, notes, and snippets.

@marvinhagemeister
Last active December 6, 2024 11:20
Show Gist options
  • Save marvinhagemeister/ca36127b2af7236e5334e5969cefa358 to your computer and use it in GitHub Desktop.
Save marvinhagemeister/ca36127b2af7236e5334e5969cefa358 to your computer and use it in GitHub Desktop.
preact use hook
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