|
|
@@ -1,9 +1,9 @@
|
|
|
import axios from 'axios';
|
|
|
-import useSWRInfinite, { SWRInfiniteResponse } from 'swr/infinite';
|
|
|
+import useSWRInfinite, { type SWRInfiniteResponse } from 'swr/infinite';
|
|
|
|
|
|
import type { LsxApiOptions, LsxApiParams, LsxApiResponseData } from '../../interfaces/api';
|
|
|
|
|
|
-import { parseNumOption } from './parse-num-option';
|
|
|
+import { type ParseNumOptionResult, parseNumOption } from './parse-num-option';
|
|
|
|
|
|
|
|
|
const LOADMORE_PAGES_NUM = 10;
|
|
|
@@ -13,24 +13,38 @@ export const useSWRxLsx = (
|
|
|
pagePath: string, options?: Record<string, string|undefined>, isImmutable?: boolean,
|
|
|
): SWRInfiniteResponse<LsxApiResponseData, Error> => {
|
|
|
|
|
|
- // parse num option
|
|
|
- const initialOffsetAndLimit = options?.num != null
|
|
|
- ? parseNumOption(options.num)
|
|
|
- : null;
|
|
|
-
|
|
|
return useSWRInfinite(
|
|
|
+ // key generator
|
|
|
(pageIndex, previousPageData) => {
|
|
|
if (previousPageData != null && previousPageData.pages.length === 0) return null;
|
|
|
|
|
|
+ // parse num option
|
|
|
+ let initialOffsetAndLimit: ParseNumOptionResult | null = null;
|
|
|
+ let parseError: Error | undefined;
|
|
|
+ try {
|
|
|
+ initialOffsetAndLimit = options?.num != null
|
|
|
+ ? parseNumOption(options.num)
|
|
|
+ : null;
|
|
|
+ }
|
|
|
+ catch (err) {
|
|
|
+ parseError = err;
|
|
|
+ }
|
|
|
+
|
|
|
// the first loading
|
|
|
if (pageIndex === 0 || previousPageData == null) {
|
|
|
- return ['/_api/lsx', pagePath, options, initialOffsetAndLimit?.offset, initialOffsetAndLimit?.limit, isImmutable];
|
|
|
+ return ['/_api/lsx', pagePath, options, initialOffsetAndLimit?.offset, initialOffsetAndLimit?.limit, parseError?.message, isImmutable];
|
|
|
}
|
|
|
|
|
|
// loading more
|
|
|
- return ['/_api/lsx', pagePath, options, previousPageData.cursor, LOADMORE_PAGES_NUM, isImmutable];
|
|
|
+ return ['/_api/lsx', pagePath, options, previousPageData.cursor, LOADMORE_PAGES_NUM, parseError?.message, isImmutable];
|
|
|
},
|
|
|
- async([endpoint, pagePath, options, offset, limit]) => {
|
|
|
+
|
|
|
+ // fetcher
|
|
|
+ async([endpoint, pagePath, options, offset, limit, parseErrorMessage]) => {
|
|
|
+ if (parseErrorMessage != null) {
|
|
|
+ throw new Error(parseErrorMessage);
|
|
|
+ }
|
|
|
+
|
|
|
const apiOptions = Object.assign({}, options, { num: undefined }) as LsxApiOptions;
|
|
|
const params: LsxApiParams = {
|
|
|
pagePath,
|
|
|
@@ -49,6 +63,8 @@ export const useSWRxLsx = (
|
|
|
throw err;
|
|
|
}
|
|
|
},
|
|
|
+
|
|
|
+ // options
|
|
|
{
|
|
|
keepPreviousData: true,
|
|
|
revalidateIfStale: !isImmutable,
|