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