@hyper-fetch/react 9.5.2 → 9.6.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/__tests__/features/helpers/use-request-events/use-request-events.async-mapper.spec.ts +243 -0
- package/__tests__/features/use-fetch/use-fetch.cancel.spec.ts +6 -3
- package/__tests__/features/use-fetch/use-fetch.debounce.spec.ts +72 -80
- package/__tests__/features/use-fetch/use-fetch.refresh.spec.ts +36 -13
- package/__tests__/features/use-fetch/use-fetch.utils.spec.ts +11 -2
- package/__tests__/features/use-infinite-fetch/use-infinite-fetch.base.spec.tsx +745 -0
- package/__tests__/features/use-infinite-fetch/use-infinite-fetch.boundaries.spec.tsx +362 -0
- package/__tests__/features/use-infinite-fetch/use-infinite-fetch.edge.spec.tsx +1043 -0
- package/__tests__/features/use-infinite-fetch/use-infinite-fetch.matrix.spec.tsx +441 -0
- package/__tests__/features/use-infinite-fetch/use-infinite-fetch.random.spec.tsx +121 -0
- package/__tests__/features/use-infinite-fetch/use-infinite-fetch.refetch.spec.tsx +567 -0
- package/__tests__/features/use-infinite-fetch/use-infinite-fetch.start-over.spec.tsx +353 -0
- package/__tests__/features/use-infinite-fetch/use-infinite-fetch.typescript.spec.ts +128 -0
- package/__tests__/features/use-is-fetching/use-is-fetching.base.spec.tsx +19 -9
- package/__tests__/features/use-submit/use-submit.concurrency.spec.ts +2 -1
- package/__tests__/features/use-submit/use-submit.debounce.spec.ts +100 -124
- package/__tests__/features/use-submit/use-submit.optimistic-settlement.spec.ts +2 -1
- package/__tests__/features/use-submit/use-submit.retry.spec.ts +51 -35
- package/__tests__/features/use-submit/use-submit.unmount.spec.ts +311 -0
- package/__tests__/utils/use-infinite-fetch.modes.ts +131 -0
- package/__tests__/utils/use-infinite-fetch.utils.ts +90 -0
- package/__tests__/utils/use-queue.utils.ts +8 -4
- package/dist/helpers/use-request-events/use-request-events.hooks.d.ts.map +1 -1
- package/dist/hooks/use-infinite-fetch/index.d.ts +4 -0
- package/dist/hooks/use-infinite-fetch/index.d.ts.map +1 -0
- package/dist/hooks/use-infinite-fetch/use-infinite-fetch.constants.d.ts +22 -0
- package/dist/hooks/use-infinite-fetch/use-infinite-fetch.constants.d.ts.map +1 -0
- package/dist/hooks/use-infinite-fetch/use-infinite-fetch.hooks.d.ts +21 -0
- package/dist/hooks/use-infinite-fetch/use-infinite-fetch.hooks.d.ts.map +1 -0
- package/dist/hooks/use-infinite-fetch/use-infinite-fetch.requests.d.ts +19 -0
- package/dist/hooks/use-infinite-fetch/use-infinite-fetch.requests.d.ts.map +1 -0
- package/dist/hooks/use-infinite-fetch/use-infinite-fetch.store.d.ts +119 -0
- package/dist/hooks/use-infinite-fetch/use-infinite-fetch.store.d.ts.map +1 -0
- package/dist/hooks/use-infinite-fetch/use-infinite-fetch.store.types.d.ts +48 -0
- package/dist/hooks/use-infinite-fetch/use-infinite-fetch.store.types.d.ts.map +1 -0
- package/dist/hooks/use-infinite-fetch/use-infinite-fetch.types.d.ts +172 -0
- package/dist/hooks/use-infinite-fetch/use-infinite-fetch.types.d.ts.map +1 -0
- package/dist/hooks/use-infinite-fetch/use-infinite-fetch.utils.d.ts +15 -0
- package/dist/hooks/use-infinite-fetch/use-infinite-fetch.utils.d.ts.map +1 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.mjs +917 -3
- package/dist/index.mjs.map +1 -1
- package/dist/provider/provider.types.d.ts +2 -0
- package/dist/provider/provider.types.d.ts.map +1 -1
- package/package.json +1 -1
- package/src/helpers/use-request-events/use-request-events.hooks.ts +17 -5
- package/src/hooks/use-infinite-fetch/index.ts +3 -0
- package/src/hooks/use-infinite-fetch/use-infinite-fetch.constants.ts +25 -0
- package/src/hooks/use-infinite-fetch/use-infinite-fetch.hooks.ts +389 -0
- package/src/hooks/use-infinite-fetch/use-infinite-fetch.requests.ts +98 -0
- package/src/hooks/use-infinite-fetch/use-infinite-fetch.store.ts +780 -0
- package/src/hooks/use-infinite-fetch/use-infinite-fetch.store.types.ts +49 -0
- package/src/hooks/use-infinite-fetch/use-infinite-fetch.types.ts +195 -0
- package/src/hooks/use-infinite-fetch/use-infinite-fetch.utils.ts +44 -0
- package/src/index.ts +1 -0
- package/src/provider/provider.types.ts +3 -0
- package/__tests__/features/use-fetch/use-fetch.infinite.ts +0 -39
package/dist/index.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import React, { useCallback, useContext, useEffect, useLayoutEffect, useMemo, useRef, useState, useSyncExternalStore } from "react";
|
|
2
|
-
import { Request, Time, getRequestDispatcher, parseResponse, replaceEqualDeep, runResponseMapper, scopeKey, sendRequest } from "@hyper-fetch/core";
|
|
2
|
+
import { Request, Time, getCachedPages, getErrorMessage, getHasNextPage, getHasPreviousPage, getInitialPageParam, getNextPageParam, getPageItems, getPageRequest, getPageTotal, getPaginationMode, getPreviousPageParam, getRequestDispatcher, mapResponseForSend, parseResponse, replaceEqualDeep, runResponseMapper, scopeKey, sendRequest, stringifyKey } from "@hyper-fetch/core";
|
|
3
3
|
import { jsxDEV } from "react/jsx-dev-runtime";
|
|
4
4
|
import { getDeliveryKey } from "@hyper-fetch/sockets";
|
|
5
5
|
//#region ../../node_modules/.pnpm/@better-hooks+lifecycle@2.0.0_react@19.2.5/node_modules/@better-hooks/lifecycle/dist/index.esm.js
|
|
@@ -38,6 +38,13 @@ var o = function(t) {
|
|
|
38
38
|
return r + 1;
|
|
39
39
|
}));
|
|
40
40
|
}), []);
|
|
41
|
+
}, a$1 = function() {
|
|
42
|
+
var t = useRef(!0);
|
|
43
|
+
return useEffect((function() {
|
|
44
|
+
return t.current = !0, function() {
|
|
45
|
+
t.current = !1;
|
|
46
|
+
};
|
|
47
|
+
}), []), t;
|
|
41
48
|
}, d$1 = function(r) {
|
|
42
49
|
useEffect((function() {
|
|
43
50
|
return r;
|
|
@@ -148,6 +155,7 @@ var useRequestEvents = ({ request, dispatcher, logger, actions, setCacheData, ge
|
|
|
148
155
|
const onUploadProgressCallback = useRef(null);
|
|
149
156
|
const lifecycleEvents = useRef(/* @__PURE__ */ new Map());
|
|
150
157
|
const dataEvents = useRef(null);
|
|
158
|
+
const isMounted = a$1();
|
|
151
159
|
const removeLifecycleListener = (requestId) => {
|
|
152
160
|
lifecycleEvents.current.get(requestId)?.unmount();
|
|
153
161
|
lifecycleEvents.current.delete(requestId);
|
|
@@ -229,9 +237,11 @@ var useRequestEvents = ({ request, dispatcher, logger, actions, setCacheData, ge
|
|
|
229
237
|
return (values) => {
|
|
230
238
|
const data = runResponseMapper(request, values.response);
|
|
231
239
|
if (data instanceof Promise) return (async () => {
|
|
240
|
+
const response = await data;
|
|
241
|
+
if (!isMounted.current) return;
|
|
232
242
|
handleResponseCallbacks({
|
|
233
243
|
...values,
|
|
234
|
-
response
|
|
244
|
+
response
|
|
235
245
|
});
|
|
236
246
|
})();
|
|
237
247
|
return handleResponseCallbacks(values);
|
|
@@ -246,6 +256,7 @@ var useRequestEvents = ({ request, dispatcher, logger, actions, setCacheData, ge
|
|
|
246
256
|
dataEvents.current = null;
|
|
247
257
|
};
|
|
248
258
|
const addCacheDataListener = (req) => {
|
|
259
|
+
if (!isMounted.current) return () => void 0;
|
|
249
260
|
const loadingUnmount = requestManager.events.onLoadingByQueue(req.queryKey, handleGetLoadingEvent(req));
|
|
250
261
|
const getResponseUnmount = cache.events.onDataByKey(req.cacheKey, (cacheData) => {
|
|
251
262
|
if (!isSameScope(cacheData.scope, req.scope)) return;
|
|
@@ -260,6 +271,7 @@ var useRequestEvents = ({ request, dispatcher, logger, actions, setCacheData, ge
|
|
|
260
271
|
return unmount;
|
|
261
272
|
};
|
|
262
273
|
const addLifecycleListeners = (req, requestId, optimisticResult) => {
|
|
274
|
+
if (!isMounted.current) return () => void 0;
|
|
263
275
|
/**
|
|
264
276
|
* useFetch handles requesting by general keys
|
|
265
277
|
* This makes it possible to deduplicate requests from different places and share data
|
|
@@ -1502,6 +1514,908 @@ var useFetchDefaultOptions = {
|
|
|
1502
1514
|
throwOnError: false
|
|
1503
1515
|
};
|
|
1504
1516
|
//#endregion
|
|
1517
|
+
//#region src/hooks/use-infinite-fetch/use-infinite-fetch.constants.ts
|
|
1518
|
+
var useInfiniteFetchDefaultOptions = {
|
|
1519
|
+
suspense: false,
|
|
1520
|
+
throwOnError: false,
|
|
1521
|
+
dependencies: [],
|
|
1522
|
+
disabled: false,
|
|
1523
|
+
dependencyTracking: true,
|
|
1524
|
+
revalidate: false,
|
|
1525
|
+
keepPreviousData: "auto",
|
|
1526
|
+
refresh: false,
|
|
1527
|
+
refreshTime: Time.HOUR,
|
|
1528
|
+
refetchBlurred: true,
|
|
1529
|
+
refetchOnBlur: false,
|
|
1530
|
+
refetchOnFocus: false,
|
|
1531
|
+
refetchOnReconnect: false,
|
|
1532
|
+
structuralSharing: true,
|
|
1533
|
+
bounce: false,
|
|
1534
|
+
bounceType: "debounce",
|
|
1535
|
+
bounceTime: 400,
|
|
1536
|
+
bounceTimeout: 400
|
|
1537
|
+
};
|
|
1538
|
+
//#endregion
|
|
1539
|
+
//#region src/hooks/use-infinite-fetch/use-infinite-fetch.requests.ts
|
|
1540
|
+
/**
|
|
1541
|
+
* Cancelled pages are not failures: the list simply did not need them anymore
|
|
1542
|
+
*/
|
|
1543
|
+
var isCancelledResponse = (response) => {
|
|
1544
|
+
const message = response?.error?.message;
|
|
1545
|
+
return !response?.success && (message === getErrorMessage("abort").message || message === getErrorMessage("deleted").message);
|
|
1546
|
+
};
|
|
1547
|
+
/**
|
|
1548
|
+
* Joins a request started elsewhere. Cancelling only stops waiting, the request belongs to someone else.
|
|
1549
|
+
*/
|
|
1550
|
+
var waitForResponse = (request, requestId, cancellers) => {
|
|
1551
|
+
const { requestManager } = request.client;
|
|
1552
|
+
return new Promise((resolve) => {
|
|
1553
|
+
const finish = (response) => {
|
|
1554
|
+
unmountResponse();
|
|
1555
|
+
unmountRemove();
|
|
1556
|
+
cancellers.delete(cancel);
|
|
1557
|
+
resolve(response);
|
|
1558
|
+
};
|
|
1559
|
+
const cancel = () => finish(null);
|
|
1560
|
+
const unmountResponse = requestManager.events.onResponseById(requestId, ({ response, details }) => {
|
|
1561
|
+
if (response.success || !details.willRetry && !details.isOffline) finish(response);
|
|
1562
|
+
});
|
|
1563
|
+
const unmountRemove = requestManager.events.onRemoveById(requestId, cancel);
|
|
1564
|
+
cancellers.add(cancel);
|
|
1565
|
+
});
|
|
1566
|
+
};
|
|
1567
|
+
var sendPage = async ({ request, force, cancellers }) => {
|
|
1568
|
+
const { fetchDispatcher } = request.client;
|
|
1569
|
+
const pageRequest = force ? request.setDeduplicate(false) : request;
|
|
1570
|
+
let sentRequestId = "";
|
|
1571
|
+
const cancel = () => {
|
|
1572
|
+
fetchDispatcher.delete(scopeKey(request.queryKey, request.scope), sentRequestId, scopeKey(request.abortKey, request.scope));
|
|
1573
|
+
};
|
|
1574
|
+
cancellers.add(cancel);
|
|
1575
|
+
const response = await pageRequest.send({
|
|
1576
|
+
dispatcherType: "fetch",
|
|
1577
|
+
onBeforeSent: ({ requestId }) => {
|
|
1578
|
+
sentRequestId = requestId;
|
|
1579
|
+
}
|
|
1580
|
+
});
|
|
1581
|
+
cancellers.delete(cancel);
|
|
1582
|
+
return response;
|
|
1583
|
+
};
|
|
1584
|
+
/**
|
|
1585
|
+
* Loads a page, reusing the request already running for it
|
|
1586
|
+
*/
|
|
1587
|
+
var loadPage = async (options) => {
|
|
1588
|
+
const { request, force, cancellers, isCancelled } = options;
|
|
1589
|
+
if (!force) {
|
|
1590
|
+
const running = request.client.fetchDispatcher.getRunningRequests(scopeKey(request.queryKey, request.scope)).find((item) => item.request.cacheKey === request.cacheKey);
|
|
1591
|
+
if (running) {
|
|
1592
|
+
const response = await waitForResponse(request, running.requestId, cancellers);
|
|
1593
|
+
if (response) return mapResponseForSend(request, response);
|
|
1594
|
+
if (isCancelled()) return null;
|
|
1595
|
+
}
|
|
1596
|
+
}
|
|
1597
|
+
return sendPage(options);
|
|
1598
|
+
};
|
|
1599
|
+
//#endregion
|
|
1600
|
+
//#region src/hooks/use-infinite-fetch/use-infinite-fetch.store.ts
|
|
1601
|
+
var unusedStoreTime = 1e3;
|
|
1602
|
+
var stores = /* @__PURE__ */ new WeakMap();
|
|
1603
|
+
var getStores = (client) => {
|
|
1604
|
+
let clientStores = stores.get(client);
|
|
1605
|
+
if (!clientStores) {
|
|
1606
|
+
clientStores = /* @__PURE__ */ new Map();
|
|
1607
|
+
stores.set(client, clientStores);
|
|
1608
|
+
}
|
|
1609
|
+
return clientStores;
|
|
1610
|
+
};
|
|
1611
|
+
var isSameSnapshot = (a, b) => {
|
|
1612
|
+
return Object.keys(a).every((key) => a[key] === b[key]);
|
|
1613
|
+
};
|
|
1614
|
+
/**
|
|
1615
|
+
* State of a single list. Hooks showing the same list share one store, so they stay in sync and never request
|
|
1616
|
+
* the same page twice. Pages are ordinary requests under their own cache keys - nothing extra is stored.
|
|
1617
|
+
*
|
|
1618
|
+
* Fetches run one at a time: every page depends on the list as it was when its value was computed.
|
|
1619
|
+
*/
|
|
1620
|
+
var InfiniteStore = class {
|
|
1621
|
+
listeners = /* @__PURE__ */ new Set();
|
|
1622
|
+
pageListeners = /* @__PURE__ */ new Set();
|
|
1623
|
+
pages = [];
|
|
1624
|
+
droppedParams = [];
|
|
1625
|
+
queue = [];
|
|
1626
|
+
running = null;
|
|
1627
|
+
cancellers = /* @__PURE__ */ new Set();
|
|
1628
|
+
refetchedKeys = /* @__PURE__ */ new Set();
|
|
1629
|
+
unmountCacheListeners = null;
|
|
1630
|
+
unusedTimer = null;
|
|
1631
|
+
started = false;
|
|
1632
|
+
settled = false;
|
|
1633
|
+
firstFetch = Promise.resolve(null);
|
|
1634
|
+
nextPageError = false;
|
|
1635
|
+
previousPageError = false;
|
|
1636
|
+
result = {
|
|
1637
|
+
error: null,
|
|
1638
|
+
status: null,
|
|
1639
|
+
extra: null,
|
|
1640
|
+
success: false
|
|
1641
|
+
};
|
|
1642
|
+
snapshot;
|
|
1643
|
+
constructor(key, options) {
|
|
1644
|
+
this.key = key;
|
|
1645
|
+
this.options = options;
|
|
1646
|
+
getPaginationMode(options.pagination);
|
|
1647
|
+
this.restorePages();
|
|
1648
|
+
this.snapshot = this.createSnapshot();
|
|
1649
|
+
}
|
|
1650
|
+
getSnapshot = () => this.snapshot;
|
|
1651
|
+
subscribe = (listener) => {
|
|
1652
|
+
this.listeners.add(listener);
|
|
1653
|
+
if (this.listeners.size === 1) this.attach();
|
|
1654
|
+
return () => {
|
|
1655
|
+
this.listeners.delete(listener);
|
|
1656
|
+
if (this.listeners.size === 0) this.detach();
|
|
1657
|
+
};
|
|
1658
|
+
};
|
|
1659
|
+
onPage = (listener) => {
|
|
1660
|
+
this.pageListeners.add(listener);
|
|
1661
|
+
return () => {
|
|
1662
|
+
this.pageListeners.delete(listener);
|
|
1663
|
+
};
|
|
1664
|
+
};
|
|
1665
|
+
/** Callbacks can capture values of the latest render */
|
|
1666
|
+
setPagination = (pagination) => {
|
|
1667
|
+
this.options.pagination = pagination;
|
|
1668
|
+
};
|
|
1669
|
+
hasPages = () => this.pages.length > 0;
|
|
1670
|
+
/**
|
|
1671
|
+
* Loads the list when it is first needed. Safe to call many times.
|
|
1672
|
+
*/
|
|
1673
|
+
start = ({ revalidate } = {}) => {
|
|
1674
|
+
if (this.started) return this.firstFetch;
|
|
1675
|
+
this.started = true;
|
|
1676
|
+
if (this.pages.length === 0) this.firstFetch = this.schedule("initial");
|
|
1677
|
+
else if (revalidate || this.getHasStalePages()) this.revalidate();
|
|
1678
|
+
else this.settled = true;
|
|
1679
|
+
this.publish();
|
|
1680
|
+
return this.firstFetch;
|
|
1681
|
+
};
|
|
1682
|
+
fetchNextPage = () => this.fetchDirection("next");
|
|
1683
|
+
fetchPreviousPage = () => this.fetchDirection("previous");
|
|
1684
|
+
/**
|
|
1685
|
+
* Refetch asked for by the user: anything already refetching is older than this call and gets replaced.
|
|
1686
|
+
*/
|
|
1687
|
+
refetch = () => {
|
|
1688
|
+
if (this.pages.length === 0) return this.revalidate();
|
|
1689
|
+
this.getOperations("refetch").forEach(this.cancelOperation);
|
|
1690
|
+
return this.schedule("refetch");
|
|
1691
|
+
};
|
|
1692
|
+
/**
|
|
1693
|
+
* Automatic refetch: joins the one in progress
|
|
1694
|
+
*/
|
|
1695
|
+
revalidate = () => {
|
|
1696
|
+
const kind = this.pages.length > 0 ? "refetch" : "initial";
|
|
1697
|
+
return this.getOperations(kind)[0]?.promise ?? this.schedule(kind);
|
|
1698
|
+
};
|
|
1699
|
+
reset = () => {
|
|
1700
|
+
this.cancelOperations();
|
|
1701
|
+
const startParam = stringifyKey(getInitialPageParam(this.options.request, this.options.pagination));
|
|
1702
|
+
this.pages = this.pages.filter((page) => stringifyKey(page.param) === startParam);
|
|
1703
|
+
this.droppedParams = [];
|
|
1704
|
+
this.nextPageError = false;
|
|
1705
|
+
this.previousPageError = false;
|
|
1706
|
+
this.settled = false;
|
|
1707
|
+
this.started = true;
|
|
1708
|
+
return this.schedule(this.pages.length > 0 ? "refetch" : "initial");
|
|
1709
|
+
};
|
|
1710
|
+
abort = () => {
|
|
1711
|
+
this.cancelOperations();
|
|
1712
|
+
this.settled = true;
|
|
1713
|
+
this.publish();
|
|
1714
|
+
};
|
|
1715
|
+
/** The list is no longer on screen - stop fetching its pages */
|
|
1716
|
+
cancelIfUnused = () => {
|
|
1717
|
+
if (this.listeners.size === 0) this.cancelOperations();
|
|
1718
|
+
};
|
|
1719
|
+
/** A store that threw its error starts over when the Error Boundary renders the component again */
|
|
1720
|
+
evictSoon = () => {
|
|
1721
|
+
setTimeout(this.evict, 0);
|
|
1722
|
+
};
|
|
1723
|
+
/** Stores created while rendering are removed when the component never mounts */
|
|
1724
|
+
scheduleUnusedCheck = () => {
|
|
1725
|
+
this.unusedTimer = setTimeout(() => {
|
|
1726
|
+
this.unusedTimer = null;
|
|
1727
|
+
if (this.running || this.queue.length > 0) this.scheduleUnusedCheck();
|
|
1728
|
+
else this.evict();
|
|
1729
|
+
}, unusedStoreTime);
|
|
1730
|
+
};
|
|
1731
|
+
fetchDirection = (kind) => {
|
|
1732
|
+
if (this.pages.length === 0) return this.getOperations("initial")[0]?.promise ?? Promise.resolve(null);
|
|
1733
|
+
const scheduled = this.getOperations(kind)[0];
|
|
1734
|
+
if (scheduled) return scheduled.promise;
|
|
1735
|
+
if (kind === "next" ? this.getNextParam() === void 0 : !this.getPreviousTarget()) return Promise.resolve(null);
|
|
1736
|
+
if (kind === "next") this.nextPageError = false;
|
|
1737
|
+
else this.previousPageError = false;
|
|
1738
|
+
return this.schedule(kind);
|
|
1739
|
+
};
|
|
1740
|
+
getOperations = (kind) => {
|
|
1741
|
+
return (this.running ? [this.running, ...this.queue] : this.queue).filter((operation) => operation.kind === kind && !operation.cancelled);
|
|
1742
|
+
};
|
|
1743
|
+
schedule = (kind) => {
|
|
1744
|
+
const operation = {
|
|
1745
|
+
kind,
|
|
1746
|
+
cancelled: false
|
|
1747
|
+
};
|
|
1748
|
+
operation.promise = new Promise((resolve) => {
|
|
1749
|
+
operation.resolve = resolve;
|
|
1750
|
+
});
|
|
1751
|
+
if (kind === "initial") this.settled = false;
|
|
1752
|
+
this.queue.push(operation);
|
|
1753
|
+
this.pump();
|
|
1754
|
+
this.publish();
|
|
1755
|
+
return operation.promise;
|
|
1756
|
+
};
|
|
1757
|
+
pump = async () => {
|
|
1758
|
+
if (this.running) return;
|
|
1759
|
+
const operation = this.queue.shift();
|
|
1760
|
+
if (!operation) return;
|
|
1761
|
+
this.running = operation;
|
|
1762
|
+
const previousPages = this.pages;
|
|
1763
|
+
let response = null;
|
|
1764
|
+
try {
|
|
1765
|
+
response = await this.perform(operation);
|
|
1766
|
+
} catch (error) {
|
|
1767
|
+
this.setFailure(error);
|
|
1768
|
+
}
|
|
1769
|
+
this.keepValidPages(previousPages);
|
|
1770
|
+
this.running = null;
|
|
1771
|
+
this.refetchedKeys.clear();
|
|
1772
|
+
if ((operation.kind === "initial" || operation.kind === "refetch") && !operation.cancelled) this.settled = true;
|
|
1773
|
+
operation.resolve(operation.cancelled ? null : response);
|
|
1774
|
+
this.pump();
|
|
1775
|
+
this.publish();
|
|
1776
|
+
};
|
|
1777
|
+
cancelOperation = (operation) => {
|
|
1778
|
+
operation.cancelled = true;
|
|
1779
|
+
if (operation === this.running) {
|
|
1780
|
+
this.cancellers.forEach((cancel) => cancel());
|
|
1781
|
+
this.cancellers.clear();
|
|
1782
|
+
this.refetchedKeys.clear();
|
|
1783
|
+
} else {
|
|
1784
|
+
this.queue = this.queue.filter((item) => item !== operation);
|
|
1785
|
+
operation.resolve(null);
|
|
1786
|
+
}
|
|
1787
|
+
};
|
|
1788
|
+
cancelOperations = () => {
|
|
1789
|
+
[...this.queue, ...this.running ? [this.running] : []].forEach(this.cancelOperation);
|
|
1790
|
+
};
|
|
1791
|
+
perform = (operation) => {
|
|
1792
|
+
switch (operation.kind) {
|
|
1793
|
+
case "next": return this.performNext(operation);
|
|
1794
|
+
case "previous": return this.performPrevious(operation);
|
|
1795
|
+
case "refetch": return this.performRefetch(operation);
|
|
1796
|
+
default: return this.performInitial(operation);
|
|
1797
|
+
}
|
|
1798
|
+
};
|
|
1799
|
+
performInitial = async (operation) => {
|
|
1800
|
+
const { request, pagination } = this.options;
|
|
1801
|
+
const fetched = await this.fetchPage(operation, getInitialPageParam(request, pagination));
|
|
1802
|
+
if (!fetched) return null;
|
|
1803
|
+
this.setResult(fetched.response);
|
|
1804
|
+
if (fetched.response.success) this.pages = [this.createPage(fetched)];
|
|
1805
|
+
return fetched.response;
|
|
1806
|
+
};
|
|
1807
|
+
performNext = async (operation) => {
|
|
1808
|
+
const param = this.getNextParam();
|
|
1809
|
+
if (param === void 0) return null;
|
|
1810
|
+
const fetched = await this.fetchPage(operation, param);
|
|
1811
|
+
if (!fetched) return null;
|
|
1812
|
+
this.setResult(fetched.response);
|
|
1813
|
+
this.nextPageError = !fetched.response.success;
|
|
1814
|
+
if (fetched.response.success) {
|
|
1815
|
+
this.pages = [...this.pages, this.createPage(fetched)];
|
|
1816
|
+
this.trimPages("start");
|
|
1817
|
+
}
|
|
1818
|
+
return fetched.response;
|
|
1819
|
+
};
|
|
1820
|
+
performPrevious = async (operation) => {
|
|
1821
|
+
const target = this.getPreviousTarget();
|
|
1822
|
+
if (!target) return null;
|
|
1823
|
+
const { param } = target;
|
|
1824
|
+
const fetched = await this.fetchPage(operation, param);
|
|
1825
|
+
if (!fetched) return null;
|
|
1826
|
+
this.setResult(fetched.response);
|
|
1827
|
+
this.previousPageError = !fetched.response.success;
|
|
1828
|
+
if (fetched.response.success) {
|
|
1829
|
+
if (target.isDropped) this.droppedParams = this.droppedParams.slice(0, -1);
|
|
1830
|
+
this.pages = [this.createPage(fetched), ...this.pages];
|
|
1831
|
+
this.trimPages("end");
|
|
1832
|
+
}
|
|
1833
|
+
return fetched.response;
|
|
1834
|
+
};
|
|
1835
|
+
performRefetch = async (operation) => {
|
|
1836
|
+
const current = this.pages;
|
|
1837
|
+
current.forEach((page) => this.refetchedKeys.add(page.storageKey));
|
|
1838
|
+
return getPaginationMode(this.options.pagination) === "cursor" ? this.refetchInOrder(operation, current) : this.refetchAtOnce(operation, current);
|
|
1839
|
+
};
|
|
1840
|
+
/**
|
|
1841
|
+
* Page and offset values do not depend on other pages, so they can be requested together
|
|
1842
|
+
*/
|
|
1843
|
+
refetchAtOnce = async (operation, current) => {
|
|
1844
|
+
const results = await Promise.all(current.map((page) => this.fetchPage(operation, page.param, true)));
|
|
1845
|
+
if (operation.cancelled) return null;
|
|
1846
|
+
const last = results.find((fetched) => fetched && !fetched.response.success) ?? results.findLast(Boolean);
|
|
1847
|
+
this.pages = current.map((page, index) => {
|
|
1848
|
+
const fetched = results[index];
|
|
1849
|
+
return fetched?.response.success ? this.createPage(fetched) : page;
|
|
1850
|
+
});
|
|
1851
|
+
if (last) this.setResult(last.response);
|
|
1852
|
+
return last?.response ?? null;
|
|
1853
|
+
};
|
|
1854
|
+
/**
|
|
1855
|
+
* Every cursor comes from the page before it, and the fresh data can hold different cursors than before.
|
|
1856
|
+
* The list is replaced only when the whole chain arrived, a failure leaves it as it was.
|
|
1857
|
+
*/
|
|
1858
|
+
refetchInOrder = async (operation, current) => {
|
|
1859
|
+
const fresh = [];
|
|
1860
|
+
let param = current[0].param;
|
|
1861
|
+
let response = null;
|
|
1862
|
+
while (fresh.length < current.length) {
|
|
1863
|
+
const fetched = await this.fetchPage(operation, param, true);
|
|
1864
|
+
if (!fetched) return null;
|
|
1865
|
+
response = fetched.response;
|
|
1866
|
+
this.setResult(response);
|
|
1867
|
+
if (!response.success) return response;
|
|
1868
|
+
const page = this.createPage(fetched);
|
|
1869
|
+
fresh.push(page);
|
|
1870
|
+
const context = this.getContext(page, fresh);
|
|
1871
|
+
if (!getHasNextPage(context)) break;
|
|
1872
|
+
param = getNextPageParam(context);
|
|
1873
|
+
}
|
|
1874
|
+
this.pages = fresh;
|
|
1875
|
+
return response;
|
|
1876
|
+
};
|
|
1877
|
+
trimPages = (side) => {
|
|
1878
|
+
const { maxPages } = this.options;
|
|
1879
|
+
if (!maxPages || this.pages.length <= maxPages) return;
|
|
1880
|
+
const overflow = this.pages.length - maxPages;
|
|
1881
|
+
if (side === "start") {
|
|
1882
|
+
this.droppedParams = [...this.droppedParams, ...this.pages.slice(0, overflow).map((page) => page.param)];
|
|
1883
|
+
this.pages = this.pages.slice(overflow);
|
|
1884
|
+
} else this.pages = this.pages.slice(0, maxPages);
|
|
1885
|
+
};
|
|
1886
|
+
fetchPage = async (operation, param, force = false) => {
|
|
1887
|
+
const request = getPageRequest(this.options.request, this.options.pagination, param);
|
|
1888
|
+
const response = await loadPage({
|
|
1889
|
+
request,
|
|
1890
|
+
force,
|
|
1891
|
+
cancellers: this.cancellers,
|
|
1892
|
+
isCancelled: () => operation.cancelled
|
|
1893
|
+
});
|
|
1894
|
+
if (operation.cancelled || !response || isCancelledResponse(response)) return null;
|
|
1895
|
+
this.pageListeners.forEach((listener) => listener({
|
|
1896
|
+
response,
|
|
1897
|
+
request,
|
|
1898
|
+
param
|
|
1899
|
+
}));
|
|
1900
|
+
return {
|
|
1901
|
+
param,
|
|
1902
|
+
request,
|
|
1903
|
+
response
|
|
1904
|
+
};
|
|
1905
|
+
};
|
|
1906
|
+
getContext = (page, pages = this.pages) => ({
|
|
1907
|
+
request: this.options.request,
|
|
1908
|
+
pagination: this.options.pagination,
|
|
1909
|
+
data: page.data,
|
|
1910
|
+
param: page.param,
|
|
1911
|
+
pages: pages.map((item) => item.data)
|
|
1912
|
+
});
|
|
1913
|
+
getNextParam = () => {
|
|
1914
|
+
const last = this.pages.at(-1);
|
|
1915
|
+
if (!last || !getHasNextPage(this.getContext(last))) return;
|
|
1916
|
+
return getNextPageParam(this.getContext(last));
|
|
1917
|
+
};
|
|
1918
|
+
getPreviousTarget = () => {
|
|
1919
|
+
const first = this.pages[0];
|
|
1920
|
+
if (!first) return null;
|
|
1921
|
+
if (this.droppedParams.length > 0) return {
|
|
1922
|
+
param: this.droppedParams.at(-1),
|
|
1923
|
+
isDropped: true
|
|
1924
|
+
};
|
|
1925
|
+
if (getHasPreviousPage(this.getContext(first))) return {
|
|
1926
|
+
param: getPreviousPageParam(this.getContext(first)),
|
|
1927
|
+
isDropped: false
|
|
1928
|
+
};
|
|
1929
|
+
return null;
|
|
1930
|
+
};
|
|
1931
|
+
getHasStalePages = () => {
|
|
1932
|
+
return this.pages.some((page) => {
|
|
1933
|
+
const value = this.readValue(page.request);
|
|
1934
|
+
return !value || isStaleCacheData(value.staleTime, value.responseTimestamp);
|
|
1935
|
+
});
|
|
1936
|
+
};
|
|
1937
|
+
readValue = (request) => {
|
|
1938
|
+
const { client } = request;
|
|
1939
|
+
const storageKey = scopeKey(request.cacheKey, request.scope);
|
|
1940
|
+
return pickInitialCacheData(client.cache.get(storageKey), this.options.hydration?.get(client, storageKey));
|
|
1941
|
+
};
|
|
1942
|
+
/** Responses go through the response mapper of the request, an asynchronous one cannot be read synchronously */
|
|
1943
|
+
mapValue = (request, value) => {
|
|
1944
|
+
const mapped = request.unstable_responseMapper ? request.unstable_responseMapper(value) : value;
|
|
1945
|
+
return mapped instanceof Promise ? void 0 : mapped;
|
|
1946
|
+
};
|
|
1947
|
+
createPage = ({ param, request, response }) => {
|
|
1948
|
+
const value = this.readValue(request);
|
|
1949
|
+
const cached = value && value.responseTimestamp >= response.responseTimestamp ? this.mapValue(request, value) : null;
|
|
1950
|
+
return {
|
|
1951
|
+
param,
|
|
1952
|
+
request,
|
|
1953
|
+
storageKey: scopeKey(request.cacheKey, request.scope),
|
|
1954
|
+
data: cached?.success ? cached.data : response.data,
|
|
1955
|
+
responseTimestamp: response.responseTimestamp
|
|
1956
|
+
};
|
|
1957
|
+
};
|
|
1958
|
+
restorePages = () => {
|
|
1959
|
+
const { request, pagination, maxPages } = this.options;
|
|
1960
|
+
this.pages = getCachedPages({
|
|
1961
|
+
request,
|
|
1962
|
+
pagination,
|
|
1963
|
+
maxPages,
|
|
1964
|
+
read: (pageRequest) => {
|
|
1965
|
+
const value = this.readValue(pageRequest);
|
|
1966
|
+
const mapped = value ? this.mapValue(pageRequest, value) : null;
|
|
1967
|
+
return mapped?.success ? {
|
|
1968
|
+
...value,
|
|
1969
|
+
data: mapped.data
|
|
1970
|
+
} : null;
|
|
1971
|
+
}
|
|
1972
|
+
}).map(({ param, request: pageRequest, value }) => ({
|
|
1973
|
+
param,
|
|
1974
|
+
request: pageRequest,
|
|
1975
|
+
storageKey: scopeKey(pageRequest.cacheKey, pageRequest.scope),
|
|
1976
|
+
data: value.data,
|
|
1977
|
+
responseTimestamp: Number(value.responseTimestamp)
|
|
1978
|
+
}));
|
|
1979
|
+
};
|
|
1980
|
+
/** Picks up everything that happened between rendering and mounting */
|
|
1981
|
+
syncPages = () => {
|
|
1982
|
+
if (this.running || this.queue.length > 0) return;
|
|
1983
|
+
if (this.pages.length === 0) {
|
|
1984
|
+
this.restorePages();
|
|
1985
|
+
return;
|
|
1986
|
+
}
|
|
1987
|
+
this.pages = this.pages.map((page) => {
|
|
1988
|
+
const value = this.readValue(page.request);
|
|
1989
|
+
const mapped = value ? this.mapValue(page.request, value) : null;
|
|
1990
|
+
return mapped?.success ? {
|
|
1991
|
+
...page,
|
|
1992
|
+
data: mapped.data,
|
|
1993
|
+
responseTimestamp: Number(value?.responseTimestamp)
|
|
1994
|
+
} : page;
|
|
1995
|
+
});
|
|
1996
|
+
};
|
|
1997
|
+
setFailure = (error) => {
|
|
1998
|
+
this.result = {
|
|
1999
|
+
error,
|
|
2000
|
+
status: null,
|
|
2001
|
+
extra: null,
|
|
2002
|
+
success: false
|
|
2003
|
+
};
|
|
2004
|
+
};
|
|
2005
|
+
/**
|
|
2006
|
+
* Pagination callbacks read the data of every page. When one of them throws, the page that caused it is not
|
|
2007
|
+
* used and the error is reported instead of breaking the list.
|
|
2008
|
+
*/
|
|
2009
|
+
keepValidPages = (previousPages) => {
|
|
2010
|
+
try {
|
|
2011
|
+
this.createSnapshot();
|
|
2012
|
+
} catch (error) {
|
|
2013
|
+
this.pages = previousPages;
|
|
2014
|
+
this.setFailure(error);
|
|
2015
|
+
}
|
|
2016
|
+
};
|
|
2017
|
+
setResult = (response) => {
|
|
2018
|
+
this.result = {
|
|
2019
|
+
error: response.success ? null : response.error,
|
|
2020
|
+
status: response.status,
|
|
2021
|
+
extra: response.extra,
|
|
2022
|
+
success: response.success
|
|
2023
|
+
};
|
|
2024
|
+
};
|
|
2025
|
+
attach = () => {
|
|
2026
|
+
if (this.unusedTimer) {
|
|
2027
|
+
clearTimeout(this.unusedTimer);
|
|
2028
|
+
this.unusedTimer = null;
|
|
2029
|
+
}
|
|
2030
|
+
const { client } = this.options.request;
|
|
2031
|
+
const clientStores = getStores(client);
|
|
2032
|
+
if (!clientStores.has(this.key) && client.mode !== "server") clientStores.set(this.key, this);
|
|
2033
|
+
const { cache } = client;
|
|
2034
|
+
const unmountData = cache.events.onData(this.handleCacheData);
|
|
2035
|
+
const unmountInvalidate = cache.events.onInvalidate(this.handleCacheChange);
|
|
2036
|
+
const unmountDelete = cache.events.onDelete(this.handleCacheChange);
|
|
2037
|
+
this.unmountCacheListeners = () => {
|
|
2038
|
+
unmountData();
|
|
2039
|
+
unmountInvalidate();
|
|
2040
|
+
unmountDelete();
|
|
2041
|
+
};
|
|
2042
|
+
this.syncPages();
|
|
2043
|
+
this.publish();
|
|
2044
|
+
};
|
|
2045
|
+
detach = () => {
|
|
2046
|
+
this.unmountCacheListeners?.();
|
|
2047
|
+
this.unmountCacheListeners = null;
|
|
2048
|
+
this.evict();
|
|
2049
|
+
};
|
|
2050
|
+
evict = () => {
|
|
2051
|
+
if (this.listeners.size > 0) return;
|
|
2052
|
+
const clientStores = getStores(this.options.request.client);
|
|
2053
|
+
if (clientStores.get(this.key) === this) clientStores.delete(this.key);
|
|
2054
|
+
};
|
|
2055
|
+
handleCacheData = (value) => {
|
|
2056
|
+
const storageKey = scopeKey(value.cacheKey, value.scope ?? null);
|
|
2057
|
+
if (!value.success || this.refetchedKeys.has(storageKey)) return;
|
|
2058
|
+
const index = this.pages.findIndex((page) => page.storageKey === storageKey);
|
|
2059
|
+
const page = this.pages[index];
|
|
2060
|
+
const mapped = page ? this.mapValue(page.request, value) : null;
|
|
2061
|
+
if (!page || !mapped?.success) return;
|
|
2062
|
+
const previousPages = this.pages;
|
|
2063
|
+
this.pages = this.pages.map((item, itemIndex) => {
|
|
2064
|
+
return itemIndex === index ? {
|
|
2065
|
+
...item,
|
|
2066
|
+
data: mapped.data,
|
|
2067
|
+
responseTimestamp: Number(value.responseTimestamp)
|
|
2068
|
+
} : item;
|
|
2069
|
+
});
|
|
2070
|
+
this.keepValidPages(previousPages);
|
|
2071
|
+
this.publish();
|
|
2072
|
+
};
|
|
2073
|
+
hasInvalidation = false;
|
|
2074
|
+
/**
|
|
2075
|
+
* Invalidated data may have changed after a running refetch started, so that refetch is replaced.
|
|
2076
|
+
* Invalidating by a pattern reports every key on its own, all of them are handled by one refetch.
|
|
2077
|
+
*/
|
|
2078
|
+
handleCacheChange = (key) => {
|
|
2079
|
+
if (!this.pages.some((page) => page.storageKey === key || page.request.cacheKey === key) || this.hasInvalidation) return;
|
|
2080
|
+
this.hasInvalidation = true;
|
|
2081
|
+
queueMicrotask(() => {
|
|
2082
|
+
this.hasInvalidation = false;
|
|
2083
|
+
if (this.listeners.size > 0) this.refetch();
|
|
2084
|
+
});
|
|
2085
|
+
};
|
|
2086
|
+
createSnapshot = () => {
|
|
2087
|
+
const { structuralSharing = true } = this.options;
|
|
2088
|
+
const previous = this.snapshot;
|
|
2089
|
+
const share = (prev, next) => structuralSharing && prev ? replaceEqualDeep(prev, next) : next;
|
|
2090
|
+
const contexts = this.pages.map((page) => this.getContext(page));
|
|
2091
|
+
const last = contexts.at(-1);
|
|
2092
|
+
const totals = contexts.map(getPageTotal).filter((total) => total !== null);
|
|
2093
|
+
const operations = [...this.queue, ...this.running ? [this.running] : []].filter((item) => !item.cancelled);
|
|
2094
|
+
const isRunning = (kind) => operations.some((item) => item.kind === kind);
|
|
2095
|
+
return {
|
|
2096
|
+
items: share(previous?.items, contexts.flatMap((context) => getPageItems(context))),
|
|
2097
|
+
data: share(previous?.data, this.pages.map((page) => page.data)),
|
|
2098
|
+
pageParams: share(previous?.pageParams, this.pages.map((page) => page.param)),
|
|
2099
|
+
total: totals.length > 0 ? totals.at(-1) : null,
|
|
2100
|
+
hasNextPage: !!last && this.getNextParam() !== void 0,
|
|
2101
|
+
hasPreviousPage: !!this.getPreviousTarget(),
|
|
2102
|
+
loading: this.pages.length === 0 && !this.settled,
|
|
2103
|
+
isFetching: operations.length > 0,
|
|
2104
|
+
isRefetching: isRunning("refetch"),
|
|
2105
|
+
isFetchingNextPage: isRunning("next"),
|
|
2106
|
+
isFetchingPreviousPage: isRunning("previous"),
|
|
2107
|
+
isFetchNextPageError: this.nextPageError,
|
|
2108
|
+
isFetchPreviousPageError: this.previousPageError,
|
|
2109
|
+
...this.result
|
|
2110
|
+
};
|
|
2111
|
+
};
|
|
2112
|
+
publish = () => {
|
|
2113
|
+
const snapshot = this.createSnapshot();
|
|
2114
|
+
if (isSameSnapshot(this.snapshot, snapshot)) return;
|
|
2115
|
+
this.snapshot = snapshot;
|
|
2116
|
+
this.listeners.forEach((listener) => listener());
|
|
2117
|
+
};
|
|
2118
|
+
};
|
|
2119
|
+
/**
|
|
2120
|
+
* Returns the store of the list, shared between all the mounted hooks showing it.
|
|
2121
|
+
* Server renders never share one: a client can serve many users at the same time.
|
|
2122
|
+
*/
|
|
2123
|
+
var getInfiniteStore = (key, options) => {
|
|
2124
|
+
const { client } = options.request;
|
|
2125
|
+
if (client.mode === "server" || typeof window === "undefined") return new InfiniteStore(key, options);
|
|
2126
|
+
const clientStores = getStores(client);
|
|
2127
|
+
let store = clientStores.get(key);
|
|
2128
|
+
if (!store) {
|
|
2129
|
+
store = new InfiniteStore(key, options);
|
|
2130
|
+
clientStores.set(key, store);
|
|
2131
|
+
store.scheduleUnusedCheck();
|
|
2132
|
+
}
|
|
2133
|
+
return store;
|
|
2134
|
+
};
|
|
2135
|
+
//#endregion
|
|
2136
|
+
//#region src/hooks/use-infinite-fetch/use-infinite-fetch.utils.ts
|
|
2137
|
+
/**
|
|
2138
|
+
* Identity of a list. Everything describing the request takes part in it, so a changed filter, sort, page size
|
|
2139
|
+
* or URL param starts a new list without anything having to be listed by hand.
|
|
2140
|
+
*/
|
|
2141
|
+
var getInfiniteKey = (request, pagination, maxPages) => {
|
|
2142
|
+
return JSON.stringify([
|
|
2143
|
+
request.toJSON(),
|
|
2144
|
+
pagination,
|
|
2145
|
+
maxPages ?? null
|
|
2146
|
+
], (_key, value) => {
|
|
2147
|
+
return typeof value === "function" ? value.toString() : value;
|
|
2148
|
+
});
|
|
2149
|
+
};
|
|
2150
|
+
/**
|
|
2151
|
+
* Keeps the first occurrence of every item
|
|
2152
|
+
*/
|
|
2153
|
+
var getUniqueItems = (items, uniqueBy) => {
|
|
2154
|
+
if (uniqueBy === void 0) return items;
|
|
2155
|
+
const seen = /* @__PURE__ */ new Set();
|
|
2156
|
+
return items.filter((item) => {
|
|
2157
|
+
const identity = typeof uniqueBy === "function" ? uniqueBy({ item }) : item?.[uniqueBy];
|
|
2158
|
+
if (seen.has(identity)) return false;
|
|
2159
|
+
seen.add(identity);
|
|
2160
|
+
return true;
|
|
2161
|
+
});
|
|
2162
|
+
};
|
|
2163
|
+
/**
|
|
2164
|
+
* Decides if the previous list stays on screen while the new one loads its first page
|
|
2165
|
+
*/
|
|
2166
|
+
var getShouldKeepPreviousList = (mode, previous, current) => {
|
|
2167
|
+
if (mode === "auto") return previous.method === current.method && previous.endpoint === current.endpoint;
|
|
2168
|
+
return mode === "preserve";
|
|
2169
|
+
};
|
|
2170
|
+
//#endregion
|
|
2171
|
+
//#region src/hooks/use-infinite-fetch/use-infinite-fetch.hooks.ts
|
|
2172
|
+
var trackedSources = {
|
|
2173
|
+
items: ["items", "loading"],
|
|
2174
|
+
pages: ["data", "loading"],
|
|
2175
|
+
pageParams: ["pageParams", "loading"],
|
|
2176
|
+
total: ["total", "loading"],
|
|
2177
|
+
isPreviousData: ["data", "loading"],
|
|
2178
|
+
loading: ["data", "loading"]
|
|
2179
|
+
};
|
|
2180
|
+
var trackedKeys = [
|
|
2181
|
+
"items",
|
|
2182
|
+
"pages",
|
|
2183
|
+
"pageParams",
|
|
2184
|
+
"total",
|
|
2185
|
+
"hasNextPage",
|
|
2186
|
+
"hasPreviousPage",
|
|
2187
|
+
"loading",
|
|
2188
|
+
"isFetching",
|
|
2189
|
+
"isRefetching",
|
|
2190
|
+
"isFetchingNextPage",
|
|
2191
|
+
"isFetchingPreviousPage",
|
|
2192
|
+
"isFetchNextPageError",
|
|
2193
|
+
"isFetchPreviousPageError",
|
|
2194
|
+
"isPreviousData",
|
|
2195
|
+
"error",
|
|
2196
|
+
"status",
|
|
2197
|
+
"extra",
|
|
2198
|
+
"success"
|
|
2199
|
+
];
|
|
2200
|
+
/**
|
|
2201
|
+
* Loads a list page by page. Say which fields page through the request, and the hook takes care of the rest:
|
|
2202
|
+
* every page is a normal request under its own cache key, and the hook glues them together.
|
|
2203
|
+
*
|
|
2204
|
+
* A changed filter, sort or URL param starts a new list on its own. When to load more is up to you - call
|
|
2205
|
+
* `fetchNextPage` from a button, an intersection observer, `onEndReached` or a virtualizer.
|
|
2206
|
+
*
|
|
2207
|
+
* @param request Request instance
|
|
2208
|
+
* @param options Hook options, `pagination` is required
|
|
2209
|
+
* @returns
|
|
2210
|
+
* @example
|
|
2211
|
+
* ```tsx
|
|
2212
|
+
* const { items, hasNextPage, fetchNextPage } = useInfiniteFetch(getFeed.setQueryParams({ topic }), {
|
|
2213
|
+
* pagination: { cursor: "cursor", next: "nextCursor", items: "data" },
|
|
2214
|
+
* });
|
|
2215
|
+
* ```
|
|
2216
|
+
*/
|
|
2217
|
+
var useInfiniteFetch = (request, options) => {
|
|
2218
|
+
const { config: globalConfig } = useProvider();
|
|
2219
|
+
const { pagination, uniqueBy, maxPages, select, suspense, throwOnError, dependencies, disabled, dependencyTracking, revalidate, keepPreviousData, refresh, refreshTime, refetchBlurred, refetchOnBlur, refetchOnFocus, refetchOnReconnect, structuralSharing, bounce, bounceType, bounceTime, bounceTimeout } = {
|
|
2220
|
+
...useInfiniteFetchDefaultOptions,
|
|
2221
|
+
...globalConfig.useInfiniteFetchConfig,
|
|
2222
|
+
...options
|
|
2223
|
+
};
|
|
2224
|
+
const { client } = request;
|
|
2225
|
+
const hydration = useHydration();
|
|
2226
|
+
const requestDebounce = f({ delay: bounceTime });
|
|
2227
|
+
const requestThrottle = p({
|
|
2228
|
+
interval: bounceTime,
|
|
2229
|
+
timeout: bounceTimeout
|
|
2230
|
+
});
|
|
2231
|
+
const bounceData = bounceType === "throttle" ? requestThrottle : requestDebounce;
|
|
2232
|
+
const bounceFunction = bounceType === "throttle" ? requestThrottle.throttle : requestDebounce.debounce;
|
|
2233
|
+
const key = getInfiniteKey(request, pagination, maxPages);
|
|
2234
|
+
const storeRef = useRef(null);
|
|
2235
|
+
const storeClientRef = useRef(client);
|
|
2236
|
+
if (!storeRef.current || storeRef.current.key !== key || storeClientRef.current !== client) {
|
|
2237
|
+
storeClientRef.current = client;
|
|
2238
|
+
storeRef.current = getInfiniteStore(key, {
|
|
2239
|
+
request,
|
|
2240
|
+
pagination,
|
|
2241
|
+
maxPages,
|
|
2242
|
+
structuralSharing,
|
|
2243
|
+
hydration
|
|
2244
|
+
});
|
|
2245
|
+
}
|
|
2246
|
+
const store = storeRef.current;
|
|
2247
|
+
const usedKeys = useRef(/* @__PURE__ */ new Set()).current;
|
|
2248
|
+
const renderedRef = useRef(null);
|
|
2249
|
+
const getSnapshot = () => {
|
|
2250
|
+
const next = store.getSnapshot();
|
|
2251
|
+
const rendered = renderedRef.current;
|
|
2252
|
+
if (dependencyTracking && rendered?.store === store) {
|
|
2253
|
+
if (![...usedKeys].some((usedKey) => {
|
|
2254
|
+
return (trackedSources[usedKey] ?? [usedKey]).some((source) => rendered.snapshot[source] !== next[source]);
|
|
2255
|
+
})) return rendered.snapshot;
|
|
2256
|
+
}
|
|
2257
|
+
renderedRef.current = {
|
|
2258
|
+
store,
|
|
2259
|
+
snapshot: next
|
|
2260
|
+
};
|
|
2261
|
+
return next;
|
|
2262
|
+
};
|
|
2263
|
+
const snapshot = useSyncExternalStore(store.subscribe, getSnapshot, getSnapshot);
|
|
2264
|
+
const callbacks = useRef({});
|
|
2265
|
+
const latest = useRef({
|
|
2266
|
+
disabled,
|
|
2267
|
+
revalidate,
|
|
2268
|
+
refetchOnBlur,
|
|
2269
|
+
refetchOnFocus,
|
|
2270
|
+
refetchOnReconnect
|
|
2271
|
+
});
|
|
2272
|
+
latest.current = {
|
|
2273
|
+
disabled,
|
|
2274
|
+
revalidate,
|
|
2275
|
+
refetchOnBlur,
|
|
2276
|
+
refetchOnFocus,
|
|
2277
|
+
refetchOnReconnect
|
|
2278
|
+
};
|
|
2279
|
+
useEffect(() => {
|
|
2280
|
+
store.setPagination(pagination);
|
|
2281
|
+
});
|
|
2282
|
+
useEffect(() => {
|
|
2283
|
+
return store.onPage((event) => {
|
|
2284
|
+
if (event.response.success) callbacks.current.onSuccess?.(event);
|
|
2285
|
+
else callbacks.current.onError?.(event);
|
|
2286
|
+
callbacks.current.onFinished?.(event);
|
|
2287
|
+
});
|
|
2288
|
+
}, [store]);
|
|
2289
|
+
/**
|
|
2290
|
+
* A new list stops the pages of the previous one, so a late response never gets in the way
|
|
2291
|
+
*/
|
|
2292
|
+
const mountedStore = useRef(null);
|
|
2293
|
+
useEffect(() => {
|
|
2294
|
+
const previous = mountedStore.current;
|
|
2295
|
+
mountedStore.current = store;
|
|
2296
|
+
if (previous && previous !== store) {
|
|
2297
|
+
previous.cancelIfUnused();
|
|
2298
|
+
callbacks.current.onReset?.();
|
|
2299
|
+
}
|
|
2300
|
+
if (disabled) return;
|
|
2301
|
+
if (bounce && previous && previous !== store && !store.hasPages()) bounceFunction(() => store.start({ revalidate: latest.current.revalidate }));
|
|
2302
|
+
else store.start({ revalidate });
|
|
2303
|
+
}, [store, disabled]);
|
|
2304
|
+
i(() => {
|
|
2305
|
+
if (!disabled) store.refetch();
|
|
2306
|
+
}, dependencies);
|
|
2307
|
+
useEffect(() => {
|
|
2308
|
+
const { appManager } = client;
|
|
2309
|
+
const handle = (option) => () => {
|
|
2310
|
+
if (latest.current[option] && !latest.current.disabled) store.revalidate();
|
|
2311
|
+
};
|
|
2312
|
+
const unmountFocus = appManager.events.onFocus(handle("refetchOnFocus"));
|
|
2313
|
+
const unmountBlur = appManager.events.onBlur(handle("refetchOnBlur"));
|
|
2314
|
+
const unmountOnline = appManager.events.onOnline(handle("refetchOnReconnect"));
|
|
2315
|
+
return () => {
|
|
2316
|
+
unmountFocus();
|
|
2317
|
+
unmountBlur();
|
|
2318
|
+
unmountOnline();
|
|
2319
|
+
};
|
|
2320
|
+
}, [client, store]);
|
|
2321
|
+
useEffect(() => {
|
|
2322
|
+
if (!refresh || disabled) return;
|
|
2323
|
+
const timer = setInterval(() => {
|
|
2324
|
+
if (client.appManager.isFocused || refetchBlurred) store.revalidate();
|
|
2325
|
+
}, refreshTime);
|
|
2326
|
+
return () => clearInterval(timer);
|
|
2327
|
+
}, [
|
|
2328
|
+
client,
|
|
2329
|
+
store,
|
|
2330
|
+
refresh,
|
|
2331
|
+
refreshTime,
|
|
2332
|
+
refetchBlurred,
|
|
2333
|
+
disabled
|
|
2334
|
+
]);
|
|
2335
|
+
const previousList = useRef(null);
|
|
2336
|
+
useEffect(() => {
|
|
2337
|
+
if (snapshot.data.length > 0) previousList.current = {
|
|
2338
|
+
store,
|
|
2339
|
+
request,
|
|
2340
|
+
snapshot
|
|
2341
|
+
};
|
|
2342
|
+
});
|
|
2343
|
+
const previous = previousList.current;
|
|
2344
|
+
const isPreviousData = !disabled && snapshot.loading && snapshot.data.length === 0 && !!previous && previous.store !== store && getShouldKeepPreviousList(keepPreviousData, previous.request, request);
|
|
2345
|
+
const list = isPreviousData ? previous.snapshot : snapshot;
|
|
2346
|
+
const isServer = client.mode === "server" || typeof window === "undefined";
|
|
2347
|
+
if (suspense && !disabled && !isServer && snapshot.loading && !isPreviousData) throw store.start({ revalidate });
|
|
2348
|
+
if (throwOnError) {
|
|
2349
|
+
usedKeys.add("error");
|
|
2350
|
+
usedKeys.add("isFetching");
|
|
2351
|
+
const error = snapshot.error;
|
|
2352
|
+
if ((typeof throwOnError === "function" ? !!error && throwOnError(error) : !!error) && !snapshot.isFetching) {
|
|
2353
|
+
store.evictSoon();
|
|
2354
|
+
throw error;
|
|
2355
|
+
}
|
|
2356
|
+
}
|
|
2357
|
+
const uniqueByRef = useRef(uniqueBy);
|
|
2358
|
+
uniqueByRef.current = uniqueBy;
|
|
2359
|
+
const uniqueByKey = typeof uniqueBy === "function" ? uniqueBy.toString() : uniqueBy;
|
|
2360
|
+
const uniqueItems = useMemo(() => {
|
|
2361
|
+
return getUniqueItems(list.items, uniqueByRef.current);
|
|
2362
|
+
}, [list.items, uniqueByKey]);
|
|
2363
|
+
const selectedRef = useRef(null);
|
|
2364
|
+
let items = uniqueItems;
|
|
2365
|
+
if (select) {
|
|
2366
|
+
const selected = select({
|
|
2367
|
+
items: uniqueItems,
|
|
2368
|
+
pages: list.data
|
|
2369
|
+
});
|
|
2370
|
+
items = structuralSharing ? replaceEqualDeep(selectedRef.current, selected) : selected;
|
|
2371
|
+
selectedRef.current = items;
|
|
2372
|
+
}
|
|
2373
|
+
const actions = useMemo(() => ({
|
|
2374
|
+
fetchNextPage: () => store.fetchNextPage(),
|
|
2375
|
+
fetchPreviousPage: () => store.fetchPreviousPage(),
|
|
2376
|
+
refetch: () => store.refetch(),
|
|
2377
|
+
reset: () => {
|
|
2378
|
+
callbacks.current.onReset?.();
|
|
2379
|
+
return store.reset();
|
|
2380
|
+
},
|
|
2381
|
+
abort: () => store.abort(),
|
|
2382
|
+
onSuccess: (callback) => {
|
|
2383
|
+
callbacks.current.onSuccess = callback;
|
|
2384
|
+
},
|
|
2385
|
+
onError: (callback) => {
|
|
2386
|
+
callbacks.current.onError = callback;
|
|
2387
|
+
},
|
|
2388
|
+
onFinished: (callback) => {
|
|
2389
|
+
callbacks.current.onFinished = callback;
|
|
2390
|
+
},
|
|
2391
|
+
onReset: (callback) => {
|
|
2392
|
+
callbacks.current.onReset = callback;
|
|
2393
|
+
}
|
|
2394
|
+
}), [store]);
|
|
2395
|
+
return createTrackedProxy({
|
|
2396
|
+
items,
|
|
2397
|
+
pages: list.data,
|
|
2398
|
+
pageParams: list.pageParams,
|
|
2399
|
+
total: list.total,
|
|
2400
|
+
hasNextPage: snapshot.hasNextPage,
|
|
2401
|
+
hasPreviousPage: snapshot.hasPreviousPage,
|
|
2402
|
+
loading: !disabled && snapshot.loading && !isPreviousData,
|
|
2403
|
+
isFetching: snapshot.isFetching,
|
|
2404
|
+
isRefetching: snapshot.isRefetching,
|
|
2405
|
+
isFetchingNextPage: snapshot.isFetchingNextPage,
|
|
2406
|
+
isFetchingPreviousPage: snapshot.isFetchingPreviousPage,
|
|
2407
|
+
isFetchNextPageError: snapshot.isFetchNextPageError,
|
|
2408
|
+
isFetchPreviousPageError: snapshot.isFetchPreviousPageError,
|
|
2409
|
+
isPreviousData,
|
|
2410
|
+
error: snapshot.error,
|
|
2411
|
+
status: snapshot.status,
|
|
2412
|
+
extra: snapshot.extra,
|
|
2413
|
+
success: snapshot.success,
|
|
2414
|
+
bounce: getBounceData(bounceData),
|
|
2415
|
+
...actions
|
|
2416
|
+
}, trackedKeys, (usedKey) => usedKeys.add(usedKey));
|
|
2417
|
+
};
|
|
2418
|
+
//#endregion
|
|
1505
2419
|
//#region src/hooks/use-submit/use-submit.hooks.ts
|
|
1506
2420
|
/**
|
|
1507
2421
|
* This hook aims to mutate data on the server. Unlike useFetch, it does not fire automatically -
|
|
@@ -2287,6 +3201,6 @@ var useIsSubmitting = (client, options) => {
|
|
|
2287
3201
|
return useRunningRequestsCount(client.submitDispatcher, options);
|
|
2288
3202
|
};
|
|
2289
3203
|
//#endregion
|
|
2290
|
-
export { Hydrate, Provider, createTrackedProxy, getBounceData, getDetailsState, getInitialState, getIsInitiallyLoading, getRefreshTime, getShouldClearState, getTimestamp, getValidCacheData, initialSocketState, initialState, isEmpty, isEqual, isStaleCacheData, useAppManager, useCache, useCacheDefaultOptions, useEmitter, useFetch, useFetchDefaultOptions, useIsFetching, useIsSubmitting, useListener, useProvider, useQueue, useQueueDefaultOptions, useRequestEvents, useSocketState, useStream, useSubmit, useSubmitDefaultOptions, useTrackedState };
|
|
3204
|
+
export { Hydrate, Provider, createTrackedProxy, getBounceData, getDetailsState, getInitialState, getIsInitiallyLoading, getRefreshTime, getShouldClearState, getTimestamp, getValidCacheData, initialSocketState, initialState, isEmpty, isEqual, isStaleCacheData, useAppManager, useCache, useCacheDefaultOptions, useEmitter, useFetch, useFetchDefaultOptions, useInfiniteFetch, useInfiniteFetchDefaultOptions, useIsFetching, useIsSubmitting, useListener, useProvider, useQueue, useQueueDefaultOptions, useRequestEvents, useSocketState, useStream, useSubmit, useSubmitDefaultOptions, useTrackedState };
|
|
2291
3205
|
|
|
2292
3206
|
//# sourceMappingURL=index.mjs.map
|