UNPKG

@gqty/react

Version:

The No-GraphQL Client for React

70 lines (65 loc) 1.79 kB
'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); const web = require('@react-hookz/web'); const React = require('react'); function useThrottledAsync(asyncFn, initialValue) { const [state, setState] = React.useState({ status: "not-executed", error: void 0, result: initialValue }); const promiseRef = React.useRef(void 0); const argsRef = React.useRef(void 0); const methods = web.useSyncedRef({ execute: (...params) => { if (promiseRef.current) return promiseRef.current; argsRef.current = params; const promise = asyncFn(...params); promiseRef.current = promise; setState((s) => ({ ...s, status: "loading" })); promise.then( (result) => { if (promise === promiseRef.current) { setState((s) => ({ ...s, status: "success", error: void 0, result })); } }, (error) => { if (promise === promiseRef.current) { setState((s) => ({ ...s, status: "error", error })); } } ).finally(() => { if (promise === promiseRef.current) { promiseRef.current = void 0; } }); return promise; }, reset: () => { setState({ status: "not-executed", error: void 0, result: initialValue }); promiseRef.current = void 0; argsRef.current = void 0; } }); return [ state, React.useMemo( () => ({ execute: (...args) => methods.current.execute(...args), reset: () => methods.current.reset() }), [] ), { promise: promiseRef.current, lastArgs: argsRef.current } ]; } exports.useThrottledAsync = useThrottledAsync;