Created
August 11, 2020 13:34
-
-
Save jesusgoku/1e3ac1f41b9291bc849038760e1b0f8a to your computer and use it in GitHub Desktop.
React Hook for manage state when call a Promise
This file contains hidden or 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
/** | |
* | |
* @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