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

MUI: broadening the scope of color challenges

These are the colors I am using: import { PaletteOptions } from "@mui/material/styles"; export const palette: PaletteOptions = { primary: { 50: "#FFF5FA", 100: "#FFEBF5", 200: "#FED7EB", ...

Exploring the concept of the never type in TypeScript 2

Exploring the latest features in TypeScript 2.0, I came across the never type. It appears to be a clever method for defining the type of functions that do not have a return value. If I understand correctly, the never type can be assigned to any other type ...

What is the correct way to link an array with ngModel using ngFor loop in Angular?

Utilizing ngModel within an ngFor iteration to extract values from a single input field like this : <mat-card class="hours" > <table id="customers"> <thead > <th >Project</th> ...

Currently focused on developing vertical sliders that can be manipulated by dragging them up or down independently

https://i.stack.imgur.com/NgOKs.jpg# I am currently working on vertical sliders that require dragging up and down individually. However, when I pull on the first slider, all sliders move together. The resetAllSliders button should also work independently, ...

What is the most efficient way to find the sum of duplicates in an array based on two different properties and then return the

var data = [ { "amount": 270, "xlabel": "25-31/10", "datestatus": "past", "color": "#E74C3C", "y": 270, "date": "2020-10-31T00:00:00Z", "entityId": 1, "entityName": "Lenovo HK", "bankName": "BNP Paribas Bank", "b ...

Error: Unable to access the 'myDate' property as it is not defined

I've been working on a simple code, but I keep encountering a browser error. The expressjs logs also show an error message. TypeError: Cannot read property 'myDate' of undefined at getReportTable (XXX\dist\controllers&bsol ...

Unable to locate module, encountered a webpack alias issue while using typescript and react

I'm currently in the process of setting up aliases in webpack. My goal is to make importing components in App.js easier by replacing: ./components/layout/Header/Header with: @components/layout/Header/Header This way, I can avoid potential issues w ...

Enhancing native JavaScript types in TypeScript 1.8 with the power of global augmentation

Currently, I am working on expanding the capabilities of native JavaScript types using the new global augmentation feature in TypeScript 1.8, as detailed in this resource. However, I'm encountering difficulties when the extension functions return the ...

What is the best way to assign or convert an object of one type to another specific type?

So here's the scenario: I have an object of type 'any' and I want to assign it an object of type 'myResponse' as shown below. public obj: any; public set Result() { obj = myResponse; } Now, in another function ...

Issue with login form in IONIC: Form only functions after page is refreshed

Encountering an issue with my Ionic login form where the submit button gets disabled due to invalid form even when it's not, or sometimes displays a console error stating form is invalid along with null inputs. This problem seems to have surfaced afte ...

At what point does the constructor of an injected service in Angular execute?

When using @Injectable({providedIn: 'root'}) in Angular 7 for a service, the constructor of the service executes when exactly? Is it upon the creation of a component that utilizes it as a dependency or does it wait until a method within the servi ...

How come TypeScript doesn't recognize my MongoDB ObjectID as a valid type?

Currently, I am working with Node.js, MongoDB, and TypeScript. The code snippet below is error-free: const ObjectID = require("mongodb").ObjectID; const id = new ObjectID("5b681f5b61020f2d8ad4768d"); However, upon modifying the second line as follows: ...

Potential explanation for unexpected Typescript initialization error

I am encountering the compiler error The property 'options' is not initialized or assigned in the constructor. However, upon reviewing the code for the respective class, it is clear that this reported error does not accurately reflect the actual ...

Error in NextJs and ReactJs: Model schema has not been registered

During my project work, I came across a MissingSchemaError when attempting to query a `one to many` relationship and use `.populate()` on another model's objects. Issue Addressed in this question: MissingSchemaError: Schema hasn't been registered ...

How to access properties of objects within an array in Angular 4

Is there a method to call only the $values from each rate record in my array that I want to read? This is what I have done to access this array: async ngOnInit() { this.product$ = await this.reviewService.getReview(this.product.$key); this.key = ...

Excessive recursion detected in the HttpInterceptor module

My application uses JWT tokens for authentication, with a random secure string inside the JWT and in the database to validate the token. When a user logs out, a new random string is generated and stored in the database, rendering the JWT invalid if the str ...

What is the process for incorporating TypeScript types into a JavaScript library?

After adding p5 and @types/p5 to my project, I imported p5 in the following way: import * as p5 from 'p5' However, when I tried using p5.createImage(100, 100), I encountered this error message indicating that 'createImage' is not a re ...

How can a mock document be utilized in a unit test for an imported TypeScript dependency?

To effectively unit-test a legacy TypeScript class, I am seeking ways to mock the document object. The class has dependencies on another class (View.ts), which in turn relies on a 3rd party module that further depends on the existence of the document. The ...

Reset radio buttons upon submission without encountering any issues

How can I clear the radio button values in React without encountering errors in NextJS? I was able to successfully do it for other fields, as shown in the example below... <div className="col-md-6"> <label className="col-md-12 c ...

Leveraging jest for handling glob imports in files

My setup involves using webpack along with the webpack-import-glob-loader to import files utilizing a glob pattern. In one of my files (src/store/resources/module.ts), I have the following line: import '../../modules/resources/providers/**/*.resource. ...