Can someone help me understand why my useGetItems hook, which imports the usePagination hook, keeps repeating the first call history every time I scroll?
- /items?_page=1&_limit=40
- /items?_page=1&_limit=40
- /items?_page=2&_limit=40
- /items?_page=1&_limit=40
- /items?_page=3&_limit=40
- /items?_page=1&_limit=40
- /items?_page=4&_limit=40
- ....
I've added this method to my Items Model
export function useGetAllItems(){
return usePagination<Item>('/api/items')
}
The usePagination in my hooks.ts file looks like this:
export const usePagination = <T>(url:string){
const getKey = (pageIndex:number, prevoiusPageData: T[])=>{
pageIndex +=1
if(previousPageData && !previousPageData.length) return null
return `${url}?_page=${pageIndex}&_limit=40`
}
const {data, size, setSize, error, mute} = useSWRInfinite(getKey, fetcher)
const paginatedData: T[] = data?.flat() as T[]
const dataArrLen = data ? data.length -1 : 0
const innerDataArr = data ? data[dataArrLen] as T[]: []
const isReachedEnd = data && innerDataArr.length < 40
const loadingMore = data && typeof data[size-1] === 'undefined'
return {
paginatedDatam isRechedEnd, loadingMore, size, setSize, error, mute
}
}
The index.ts file for /api/items looks like this:
const getAllItems = async(request) => {
let { _page, _limit} = request.query
if(_page && _limit)
{
const itemsDao = new ItemDao()
let page = parseInt(_page)
let limit = parseInt (_limit)
limit = (page-1) * limit < 40 ? 40 : (page-1)*limit
const allItems = await itemsDao.getAllItems(limit)
return new JsonResult(200, allItems)
}
return new JsonResult(200, {})
}
This is what the dao looks like:
export class ItemDao extends Database{
public async getAllItems(limit: number){
const generatedData = JSON.parse(JSON.stringify(randomItems))
const itemsJson2Array = Object.values(generatedData)
const items = []
const offset = limit -40 < 0 ? 0 : limit-40
for (let i = offset; i < limit ; i++){
if(ItemsSchema.safeParse(itemsJson2Array[i].success){
items.push(itemsJson2Array[i])
}
return items
}
}
}
And here's how it's used in my itemsPage.tsx file:
const {paginatedData, setSize, isReachedEnd} = useGetAllItems()
return (
<>
<InfiniteScroll next={()=>setSize(_size=> _size+1)} hasMore=(!isReachedEnd) ... >
<ItemsCard items={paginatedData} />
</InfiniteScroll>
</>
)