You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
I am using useSWRInfinite to fetch paginated data. The original API response contains 75 entries, pagination info and status. The data returned from useSWRInfinite contains only 5 data entries at first and then after a second or so it returns complete data. I am unable to figure out why this is happening. Why is it not returning all the data in first attempt even though the API is returning correct response.
reacted with thumbs up emoji reacted with thumbs down emoji reacted with laugh emoji reacted with hooray emoji reacted with confused emoji reacted with heart emoji reacted with rocket emoji reacted with eyes emoji
-
I am using useSWRInfinite to fetch paginated data. The original API response contains 75 entries, pagination info and status. The data returned from useSWRInfinite contains only 5 data entries at first and then after a second or so it returns complete data. I am unable to figure out why this is happening. Why is it not returning all the data in first attempt even though the API is returning correct response.
` function useInfinitePagination<K, T>(
queryParams: K,
initialData: PaginatedData,
url: string,
config: SWRConfiguration = {},
) {
const [paginatedData, setPaginatedData] = useState<T[]>(initialData.data);
const [paginationInfo, _setPaginationInfo] = useState(
initialData.paginationInfo
);
const { data, error, isValidating, mutate, size, setSize } = useSWRInfinite(
(index) =>
${url}?${qs.stringify({ ...queryParams, page: index + 1 })}
,fetcher,
{ initialData: initialData.data, initialSize: 1, ...config }
);
console.log("data", data)
useEffect(() => {
setSize(1);
}, [JSON.stringify(queryParams)]);
useEffect(() => {
if (!!data?.[0]?.data) {
_setPaginationInfo(data?.[0]?.paginationInfo);
let flattenData = data?.map((item: any) => {
return item.data;
});
flattenData = [].concat.apply([], flattenData || []);
setPaginatedData(flattenData.filter(Boolean));
}
}, [data]);
console.log("hook", paginatedData)
function hasMore() {
return paginationInfo && size < paginationInfo.totalPages;
}
function resetPage() {
setSize(1);
}
function loadMore() {
if (hasMore() && !isValidating) {
setSize(size + 1);
}
}
return {
loadMore,
hasMore,
paginatedData,
error,
isValidating,
mutate,
size,
setSize,
resetPage,
paginationInfo,
};
} `
Beta Was this translation helpful? Give feedback.
All reactions