[SWRInfinte bug]: repeated api calls for initial page index
See original GitHub issueIn useSWRInfinite, our colleagues have spotted this issue that initial page is always requested repeatedly with any next page request.
Made an infinite scroller and console logged pageIndex, and url from the fetcher function. If you see attached screenshots below (in order), you can easily spot the pattern.
For every incremental page , it is making double requests - one for page 1 [initial page], and another for the next page. Changing revalidation rules in options has no effect.
Here’s the custom hook used inside the scrolling div.
_
import { KeyLoader } from “swr”; import useSWRInfinite, { SWRInfiniteConfiguration } from “swr/infinite”; export const useFeedPagination = <T>( url: string, options?: SWRInfiniteConfiguration ) => { const PAGE_SIZE = 5; const getKey: KeyLoader = (pageIndex: number, previousPageData: any[]) => { console.log(“key index ****”, pageIndex); pageIndex = pageIndex > 0 ? parseInt(previousPageData[0].postId) + 1 : 1; if (previousPageData && !previousPageData.length) return null; // reached the end return
${url}/posts/${pageIndex}/comments
; // SWR key };const fetcher = (url: RequestInfo) => { console.log(“/////”, url.toString()); if (url.toString().includes(“/posts/1/”)) { // do } return fetch(url).then((res) => res.json()); };
const { data, size: page, setSize: setPage, error, isValidating, mutate, } = useSWRInfinite(getKey, fetcher, options);
const paginatedData: T[] = [].concat.apply([], data || []);
const isLoadingMore = data && typeof data[page - 1] === “undefined”;
const isReachedEnd = data && data[data.length - 1]?.length < PAGE_SIZE; return { mutate, error, paginatedData, page, setPage, isLoadingMore, isReachedEnd, isValidating, }; };
_
_Originally posted by @VewMet in https://github.com/vercel/swr/discussions/1612#discussioncomment-1648517_
Issue Analytics
- State:
- Created 2 years ago
- Reactions:2
- Comments:9 (2 by maintainers)
Since SWR 1.1.0, there is a new option
revalidateFirstPage
that you can use to turn this off. Related docs: https://github.com/vercel/swr/releases/tag/1.1.0If you are interested, here are the full discussions of why we built this feature in the first place: https://github.com/vercel/swr/issues/1401#issuecomment-907764278, and why we now provide this new option to customize it.
Let me know if it helps you!
Yeah I ended up finding that PR and realizing it was intended. I was looking at the code for a workaround but I am glad to know that you are considering the first page revalidation optional. Thank you very much for the quick reply.