setSize not update the index params inside callback at the useSWRInfinite hooks #2709
-
In the docs that works perfectly, but I'm not sure why my code wasn't in the image above, showing that setSize not triggering the callback here's the code import { RecommendationContent } from "@bilibili-dl/interfaces/core";
import { useCallback, useEffect } from "react";
import useSWRInfinite from "swr/infinite";
export default function useRecommendation(): any {
const { data, error, isLoading, isValidating, size, setSize } =
useSWRInfinite<RecommendationContent>(
(pageIndex, prevPageData) => {
if (prevPageData && !prevPageData.length) return null;
return `/api/recommend?pn=${pageIndex + 1}`;
},
(...args) => fetch(...args).then((res) => res.json()),
{
revalidateOnFocus: false,
revalidateFirstPage: false,
}
);
const onScroll = useCallback(() => {
const { scrollTop, scrollHeight, clientHeight } = document.documentElement;
if (
Math.abs(scrollHeight - scrollTop - clientHeight) < 1 &&
!isValidating
) {
setSize((size) => ++size);
}
}, [isValidating]);
const recommend_card = data
? ([] as RecommendationContent[]).concat(...data)
: [];
useEffect(() => {
window.addEventListener("scroll", onScroll);
return () => {
console.log("called once unmounted? or re-rendered?");
window.removeEventListener("scroll", onScroll);
};
}, [isValidating]);
useEffect(() => {
console.log(size);
}, [size]);
return {
data: recommend_card,
error,
isLoading,
};
} Are there any mistakes that I am making? EDIT: I added console.log inside the callback, and it's logged! The main issue is that the index is not incremented and stuck at zero, why does this behavior occur? |
Beta Was this translation helpful? Give feedback.
Answered by
RealYukiSan
Jul 11, 2023
Replies: 1 comment
-
ah it's my fault, the code |
Beta Was this translation helpful? Give feedback.
0 replies
Answer selected by
RealYukiSan
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
ah it's my fault, the code
if (prevPageData && !prevPageData.length) return null;
prevent it from updating the keys