In the process of using SWRInfinite for React Infinite Scrolling, the initial call may be made

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>
    </>
)

Answer №1

Change the revalidateFirstPage parameter to true.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for successfully passing function variables as parameters to Angular 2 HTTP subscribe callbacks

I attempted this.propositionService.addProposition(this.proposition) .subscribe(this.addSuccessCallback, this.addFailureCallback); The issue I am encountering is that both addSuccessCallback and addFailureCallback do not have acces ...

Configuring environment variables in Next.js

I am currently in the process of configuring the ENV in Next.js Within next.config.js file const TsconfigPathsPlugin = require("tsconfig-paths-webpack-plugin"); const withSass = require('@zeit/next-sass'); module.exports = withSass({ target: ...

Ways to determine if a date matches today's date within a component template

I am currently displaying a list of news articles on the webpage and I want to show the word "Today" if the news article's date is equal to today's date. Otherwise, I want to display the full date on the page. Is there a way to compare the news.D ...

Navigating with NextJS Link and anchor takes you directly to the homepage of the website

I'm currently learning about NextJS and I am developing a page located under the /security/ path. In the file /app/security/page.jsx, there is a simple anchor tag link as shown below: <Link href="#data-storage" scroll={false}>Data Sto ...

Upgrading from Next.js version 10 to version 13: A Comprehensive Guide

Here is the content of my pages/my _app.js file: import { Provider } from 'next-auth/client'; import '../styles/globals.css'; import 'react-perfect-scrollbar/dist/css/styles.css'; import LayoutWrapper from '../components ...

Is it possible to configure Next.js to automatically redirect 404 errors from a nested [slug] path to the parent file?

Suppose that I have the following file structure: /store/index.ts /store/pants/[slug].ts Is it possible to redirect 404 errors to /store/ so that the user is directed to the parent directory instead of a 404 page? ...

Unexpected behavior: Promise.catch() fails to catch exception in AngularJS unit test

During the process of writing Jasmine unit tests for my Typescript app and running them via Resharper, I encountered an issue with executing an action when the handler throws an exception: describe("Q Service Test", () => { var q: ng.IQService; ...

The Tailwind child element set to 'h-full' is as big as the parent element set to 'h-screen', causing it to appear oversized

My webpage is built using Tailwind CSS and the code for it is as follows: <div id="parent" class="flex h-screen flex-col bg-red-600"> <div id="child1" class="flex h-20 items-center justify-center bg-green-600&q ...

Tips for transferring a calculated value from a child component to a parent component in ReactJs

In my current project, I am faced with the challenge of passing a calculated value from a child component back to its parent. The child component is designed to utilize various user inputs to compute a single value that needs to be returned to the parent. ...

Tips for accessing the app instance within a module in Nest.js

Currently, I am involved in a project that relies on multiple Nest repositories, approximately 4 in total. Each repository must integrate logging functionalities to monitor various events such as: Server lifecycle events Uncaught errors HTTP requests/resp ...

Encountering an error in Nextjs with multer: TypeError when trying to read the property 'transfer-encoding' of undefined

Recently delving into Nextjs, I encountered an issue while attempting to upload a file using multer. The error message "TypeError: Cannot read property 'transfer-encoding' of undefined" popped up. The route requires authentication via auth middle ...

Unable to resolve every parameter

I am facing an issue while trying to inject a service into my component, resulting in the following error: https://i.stack.imgur.com/zA3QB.png news.component.ts import { Component,OnInit } from '@angular/core'; import { NewsService } from &apo ...

The attribute 'name' cannot be found within the class 'MyComponent'

I'm a beginner in Angular2 and I have no previous knowledge of version 1. Can you help me understand why this error is occurring and guide me on how to fix it? import { Component } from 'angular2/core'; @Component ({ selector: 'my- ...

Having trouble retrieving the parent object in Angular OnInit method?

I am facing an issue with attaching a custom validator to an Angular Form Control. The Form Controls are initialized in the ngOnInit method, and I want the validator to check if a field has input only when a boolean class member this.shouldCheck is true. ...

Having trouble utilizing HTML Canvas in the newest release of Angular and TypeScript

After extensive searching on the internet, I have not been able to find any working examples of using HTML canvas in Angular. It seems that changes in syntax in Typescript and Angular's newer versions have rendered all existing solutions obsolete. I ...

Accessing file uploads in Angular 2

<div class="fileUpload btn btn-primary"> <span>Select File</span> <input id="uploadBtn" type="file" class="upload" value="No File Chosen" #uploadBtn/> </div> <input id="uploadFile" placeholder="No File Selected" disable ...

Utilize an alias to define the SCSS path in an Angular-CLI library project

I am in the process of developing a library project using angular-cli. I have been following the guidelines outlined in the angular documentation. This has resulted in the creation of two main folders: one is located at ./root/src/app, where I can showcase ...

Tips for preserving @typedef during the TypeScript to JavaScript transpilation process

I have a block of TypeScript code as shown below: /** * @typedef Foo * @type {Object} * @property {string} id */ type Foo = { id: string } /** * bar * @returns {Foo} */ function bar(): Foo { const foo:Foo = {id: 'foo'} return f ...

I'm having an issue with the Next.js Image component not functioning properly on the server

The issue with Next.js Image not working on the server but working fine on localhost has been puzzling me. My assumption was that it could be related to permissions, as I fetch images from a third-party domain. However, when I load images using a regular ...

What is preventing the value from changing in auth.guard?

I am encountering an issue with the variable loggined, which I modify using the logTog() method. When I call this method, a request is made to a service where the current result is passed to auth.guard. However, in the console, it displays "undefined". Can ...