dolab
Version:
Lightweight and fast React hooks library for fetching and managing data with Zustand state management. Ideal for scalable and modern React applications.
97 lines (96 loc) • 2.5 kB
JavaScript
import { useEffect as l } from "react";
import { create as h } from "zustand";
const s = 30 * 60 * 1e3, D = () => "xxxxxxx-xxxx-xxxx-xxxx-xxxxxxxx".replace(/[x]/g, (e) => {
const c = Math.random() * 16 | 0;
return (e === "x" ? c : c & 3 | 8).toString(16);
}), d = h((e, c) => ({
data: {},
loading: {},
expiry: {},
refetch: {},
setData: (n, t, o) => {
const a = Date.now() + (o ?? s);
e((r) => ({
...r,
data: {
...c().data,
[n]: t
},
expiry: {
...c().expiry,
[n]: a
}
}));
},
setLoading: (n, t) => {
e((o) => ({
...o,
loading: {
...c().loading,
[n]: t
}
}));
},
setRefetch: (n) => {
e((t) => ({
...t,
refetch: {
...t.refetch,
[n]: D()
// Trigger refetch
},
loading: {
...t.loading,
[n]: !0
}
})), setTimeout(() => {
e((t) => ({
...t,
refetch: {
...t.refetch,
[n]: void 0
// Reset refetch after execution
},
loading: {
...t.loading,
[n]: !1
}
}));
}, 1e3);
},
cleanupExpiredData: () => {
const n = Date.now();
e((t) => {
const o = { ...t.data }, a = { ...t.expiry };
return Object.entries(t.expiry).forEach(([r, x]) => {
typeof x == "number" && x <= n && (delete o[r], delete a[r]);
}), { data: o, expiry: a };
});
}
}));
function w(e) {
const c = d((i) => i.setData), n = d((i) => i.setRefetch), t = () => n(e.id), o = (i) => c(e.id, i, e.lifeTime), a = d((i) => {
const u = i.expiry[e.id];
if (!(u && u <= Date.now()))
return i.data[e.id];
}), r = d((i) => i.loading[e.id]) || !1, x = d((i) => i.refetch[e.id]) || void 0, g = d((i) => i.setLoading), f = (i) => g(e.id, i);
return l(() => {
if (!e.id) throw new Error("useDolab must have a unique id");
}, [e.id]), l(() => {
e.id && (f(!0), e.fetch(o).finally(() => f(!1)));
}, [e.id, ...e.deps || []]), l(() => {
!e.id || !x || (f(!0), e.fetch(o).finally(() => f(!1)));
}, [x]), { data: a, loading: r, triggerRefetch: t };
}
function E(e) {
const c = d((a) => {
const r = a.expiry[e.id];
if (!(r && r <= Date.now()))
return a.data[e.id];
}), n = d((a) => a.loading[e.id]) || !1, t = d((a) => a.setRefetch);
return { data: c, loading: n, triggerRefetch: () => t(e.id) };
}
export {
w as useDolab,
E as useDolabData
};