Skip to content

Instantly share code, notes, and snippets.

@quantizor
Last active June 21, 2019 19:12
Show Gist options
  • Save quantizor/4308dd5e3d3822393ea6af9633d7dfad to your computer and use it in GitHub Desktop.
Save quantizor/4308dd5e3d3822393ea6af9633d7dfad to your computer and use it in GitHub Desktop.
use-promise-hook
import { useEffect, useState } from 'react';
/**
* Pass a memoized promise getter (via useCallback) so we do not attempt to
* continuously re-request the promise.
*/
export default function usePromise(getPromise) {
const [loading, setLoading] = useState(true);
const [promise, setPromise] = useState();
const [error, setError] = useState();
const [result, setResult] = useState();
useEffect(() => {
setPromise(getPromise());
}, [getPromise]);
useEffect(() => {
let mounted = true;
if (promise)
promise
.then(res => mounted && setResult(res))
.catch(err => mounted && setError(err))
.finally(() => mounted && setLoading(false));
return () => { mounted = false; }
}, [promise]);
return {
error,
loading,
result,
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment