@adyen/adyen-platform-experience-web
Version:

40 lines (39 loc) • 1.15 kB
JavaScript
import { useRef as l, useReducer as h, useCallback as y, useEffect as g } from "../external/preact/hooks/dist/hooks.module.js";
import { boolOrTrue as f } from "../utils/value/bool.js";
function R({
fetchOptions: { keepPrevData: s, onSuccess: t, enabled: i } = { keepPrevData: !0 },
queryFn: u
}) {
const r = l(!1), a = {
error: void 0,
data: void 0,
isFetching: f(i)
}, o = (e, c) => {
switch (c.type) {
case "loading":
return { ...a, isFetching: !0, data: s ? e.data : void 0 };
case "fetched":
return { ...a, data: c.payload, isFetching: !1 };
case "error":
return { ...a, error: c.payload, isFetching: !1 };
default:
return e;
}
}, [p, n] = h(o, a), d = y(async () => {
n({ type: "loading" });
try {
if (r.current) return;
const e = await u();
t == null || t(e), n({ type: "fetched", payload: e });
} catch (e) {
if (r.current) return;
n({ type: "error", payload: e });
}
}, [n, u, t]);
return g(() => (r.current = !1, f(i) && d(), () => {
r.current = !0;
}), [i, d]), p;
}
export {
R as useFetch
};