UNPKG

bananahooks

Version:

"Collection" of custom React Hooks.

41 lines (37 loc) 1.27 kB
(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('react')) : typeof define === 'function' && define.amd ? define(['exports', 'react'], factory) : (global = global || self, factory(global.bananahooks = {}, global.React)); }(this, function (exports, React) { 'use strict'; function usePromise(promiseOrFunction, defaultValue) { const [state, setState] = React.useState({ value: defaultValue, error: null, isPending: true }); React.useEffect(() => { const promise = typeof promiseOrFunction === "function" ? promiseOrFunction() : promiseOrFunction; let isSubscribed = true; promise.then(value => isSubscribed ? setState({ value, error: null, isPending: false }) : null).catch(error => isSubscribed ? setState({ value: defaultValue, error: error, isPending: false }) : null); return () => { isSubscribed = false; }; }, [promiseOrFunction, defaultValue]); const { value, error, isPending } = state; return [value, error, isPending]; } exports.usePromise = usePromise; })); //# sourceMappingURL=bananahooks.umd.development.js.map