UNPKG

@d3vtool/hooks

Version:

Collection of custom React hooks to simplify tasks in your React projects.

2 lines (1 loc) 2.1 kB
"use strict";var l=function(e,n){var t=typeof Symbol=="function"&&e[Symbol.iterator];if(!t)return e;var a=t.call(e),r,i=[],c;try{for(;(n===void 0||n-- >0)&&!(r=a.next()).done;)i.push(r.value)}catch(u){c={error:u}}finally{try{r&&!r.done&&(t=a.return)&&t.call(a)}finally{if(c)throw c.error}}return i};import{useEffect as f,useRef as d,useState as s}from"react";export function usePromiseHub(e,n){var t,a,r=d(!1),i=d(null),c=l(s({currentState:e.getCurrentState(),pending:e.getPendingState(),error:e.getErrorState()}),2),u=c[0],v=c[1],o={immediate:(t=n?.immediate)!==null&&t!==void 0?t:!0,suspense:(a=n?.suspense)!==null&&a!==void 0?a:!1};if(f(function(){return e.attachListener(v),function(){e.detachListener(v)}},[e]),f(function(){!o.immediate||r.current||(r.current=!0,e.reAction())},[e,o.immediate]),o.suspense&&u.pending)throw new Promise(function(g){i.current instanceof Function&&i.current(),i.current=g});return o.suspense&&!u.pending&&i.current instanceof Function&&(i.current(),i.current=null),{data:u.currentState,error:u.error,isPending:u.pending,reAction:e.reAction.bind(e)}}export function usePromiseReadHub(e,n){n===void 0&&(n=!1);var t=d(null),a=l(s({currentState:e.getCurrentState(),pending:e.getPendingState(),error:e.getErrorState()}),2),r=a[0],i=a[1];if(f(function(){return e.attachListener(i),function(){e.detachListener(i)}},[e]),n&&r.pending)throw new Promise(function(c){t.current instanceof Function&&t.current(),t.current=c});return n&&!r.pending&&t.current instanceof Function&&(t.current(),t.current=null),{data:r.currentState,error:r.error,isPending:r.pending}}export function usePromiseHubAction(e,n){n===void 0&&(n=!1);var t=d(null),a=l(s({currentState:e.getCurrentState(),pending:e.getPendingState(),error:e.getErrorState()}),2),r=a[0],i=a[1];if(f(function(){return e.attachListener(i),function(){e.detachListener(i)}},[]),n&&r.pending)throw new Promise(function(c){t.current instanceof Function&&t.current(),t.current=c});return n&&!r.pending&&t.current instanceof Function&&(t.current(),t.current=null),{reAction:e.reAction.bind(e),error:r.error,isPending:r.pending}}