Skip to content

Instantly share code, notes, and snippets.

@jesusgoku
Created August 11, 2020 13:34
Show Gist options
  • Save jesusgoku/1e3ac1f41b9291bc849038760e1b0f8a to your computer and use it in GitHub Desktop.
Save jesusgoku/1e3ac1f41b9291bc849038760e1b0f8a to your computer and use it in GitHub Desktop.
React Hook for manage state when call a Promise
/**
*
* @typedef {Object} UsePromiseOptions
* @property {boolean} [lazy=false] - when true, Promise not call into first render
*
* @typedef {Object} UsePromiseState
* @property {*} data - data resolved by Promise
* @property {Error|null} error - data rejected by Promise, if exists
* @property {boolean} loading - when true, Promise is pending
* @property {Function} callPromise - manually call Promise
*/
/**
* Hook for manage state of Promise
*
* @param {Function} fn - function returned a Promise
* @param {UsePromiseOptions} options - usePromise options
*
* @returns {UsePromiseState} - state of Promise
*/
function usePromise(fn, { lazy = false } = {}) {
const [data, setData] = useState(null);
const [error, setError] = useState(null);
const [loading, setLoading] = useState(false);
const callPromise = () => {
setData(null);
setError(null);
setLoading(true);
fn()
.then((data) => { setData(data); })
.catch((err) => { setError(err); })
.then(() => { setLoading(false); })
;
}
useEffect(() => {
if (lazy) return;
callPromise();
}, []);
return { data, error, loading, callPromise };
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment