UNPKG

prostgles-client

Version:

Reactive client for Postgres

32 lines (31 loc) 1.36 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.useFetch = void 0; const reactImports_1 = require("../hooks/reactImports"); const { useState } = reactImports_1.reactImports; const useAsyncEffectQueue_1 = require("./useAsyncEffectQueue"); const useIsMounted_1 = require("./useIsMounted"); const useFetch = (fetchFunc, args = [], hookOptions) => { const { skip, deps = [] } = hookOptions !== null && hookOptions !== void 0 ? hookOptions : {}; const defaultLoadingResult = { data: undefined, error: undefined, isLoading: true }; const [{ data, error, isLoading }, setResult] = useState(defaultLoadingResult); const getIsMounted = (0, useIsMounted_1.useIsMounted)(); (0, useAsyncEffectQueue_1.useAsyncEffectQueue)(async () => { if (!getIsMounted() || skip) return; setResult(defaultLoadingResult); try { const newData = await fetchFunc(...args); if (!getIsMounted()) return; setResult({ data: newData, error: undefined, isLoading: false }); } catch (error) { if (!getIsMounted()) return; setResult({ data: undefined, error, isLoading: false }); } }, [fetchFunc, ...args, ...deps]); return { data, error, isLoading }; }; exports.useFetch = useFetch;