From f852255d8260e5f19ac5ba81328371f025c30a7e Mon Sep 17 00:00:00 2001 From: schroda <50052685+schroda@users.noreply.github.com> Date: Sun, 28 May 2023 02:18:23 +0200 Subject: [PATCH] Add additional info about SWR infinite load to response (#321) The SWR response only has "isLoading" and "isValidating". "isLoading" only indicates the initial load. For every subsequent load, only "isValidating" gets set to true. --- src/lib/RequestManager.ts | 27 ++++++++++++++++++--------- 1 file changed, 18 insertions(+), 9 deletions(-) diff --git a/src/lib/RequestManager.ts b/src/lib/RequestManager.ts index d04f8eef..0a7b0c9b 100644 --- a/src/lib/RequestManager.ts +++ b/src/lib/RequestManager.ts @@ -52,10 +52,16 @@ type CustomSWROptions = { type SWROptions = SWRConfiguration & CustomSWROptions; type SWRInfiniteOptions = SWRInfiniteConfiguration & CustomSWROptions; +type SWRInfiniteResponseLoadInfo = { + isInitialLoad: boolean; + isLoadMore: boolean; +}; type AbortableRequest = { abortRequest: AbortController['abort'] }; type AbortableAxiosResponse = { response: Promise> } & AbortableRequest; type AbortableSWRResponse = SWRResponse & AbortableRequest; -type AbortableSWRInfiniteResponse = SWRInfiniteResponse & AbortableRequest; +type AbortableSWRInfiniteResponse = SWRInfiniteResponse & + AbortableRequest & + SWRInfiniteResponseLoadInfo; // the following endpoints have not been implemented: // - PUT /api/v1/manga/{mangaId}/chapter/{chapterIndex} - modify chapter # PATCH endpoint used instead @@ -144,11 +150,11 @@ export class RequestManager { axiosOptions, swrOptions, }: { data?: any; axiosOptions?: AxiosRequestConfig; swrOptions?: OptionsSWR } = {}, - ): SWRInfiniteResponse { + ): SWRInfiniteResponse & SWRInfiniteResponseLoadInfo { const { skipRequest, ...swrConfig } = swrOptions ?? {}; // useSWRInfinite will (by default) revalidate the first page, to check if the other pages have to be revalidated as well - const result = useSWRInfinite( + const swrResult = useSWRInfinite( (index, previousData) => { const pageEndpoint = getEndpoint(index, previousData); return pageEndpoint !== null && !skipRequest ? this.getValidUrlFor(pageEndpoint) : null; @@ -159,14 +165,17 @@ export class RequestManager { }, ); - return { - ...result, + const isNextPageMissing = !!swrResult.data && typeof swrResult.data[swrResult.size - 1] === 'undefined'; + const isLoadingMore = swrResult.size > 0 && isNextPageMissing; + const customSwrResult = { + ...swrResult, + isInitialLoad: swrResult.isLoading, // SWR "isLoading" state is only updated for the first load, for every subsequent load it's "false" - isLoading: - result.isLoading || - // check if more data is being loaded - (result.size > 0 && !!result.data && typeof result.data[result.size - 1] === 'undefined'), + isLoadMore: !swrResult.isLoading && isLoadingMore, }; + customSwrResult.isLoading = customSwrResult.isInitialLoad || customSwrResult.isLoadMore; + + return customSwrResult; } /**