What steps should I take to incorporate lazy loading into my PrimeReact DataTable?

I want to showcase data in a PrimeReact (v9.3.1) DataTable with lazy loading feature. Here is the code snippet:

const [questionAnswerValues, setQuestionAnswerValues] = useState([]);
const [editedRow, setEditedRow] = useState<any>({});
const [selectedRow, setSelectedRow] = useState<any>({});
const [lazyLoading, setLazyLoading] = useState(false);

useEffect(() => {
    fetchRange(0,20);
}, []);

const fetchRange = (first: number, last: number) => {
    fetch(`/api/questionanswer/slice?first=${first}&last=${last}`).then((response) => response.json()).then(data => {
        console.log(data);
        data = [...questionAnswerValues, data];
        //setQuestionAnswerValues(data); //generate infinite render requests !!!
        setLazyLoading(false);
    });
}
const loadQuestionAnswerLazy = (event: any) => {
    console.log(JSON.stringify(event));
    let { first, last } = event;
    if (last !== 0) {
        fetchRange(first, last);
    }
}

The Data table displays as follows:

        <DataTable value={questionAnswerValues} responsiveLayout="scroll" selectionMode="single" selection={selectedRow}
            onSelectionChange={(e) => setSelectedRow(e.value)} scrollable scrollHeight="400px"
            virtualScrollerOptions={{ lazy: true, onLazyLoad: loadQuestionAnswerLazy, itemSize: 46, delay: 200, showLoader: true, loading: lazyLoading }}
            tableStyle={{ minWidth: '50rem' }}>
            <Column selectionMode="single" header="Select one"></Column>
            <Column field="_id" header="ID"></Column>
            <Column field="question_id.question" header="Question"></Column>
            <Column field="answer" header="Answer"></Column>
            <Column field="isCorrect" header="IsCorrect"></Column>
        </DataTable>

First query: How can I update data values without triggering infinite renders?

Second question: Using data = [...questionAnswerValues, data] seems impractical. What's an alternative method to append data to questionAnswerValues?

Third query: Is there a React datatable implementation that can display newly added records without hiding existing ones?

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

Testing Angular 16 Component with Jasmine Spy and callFake Strategy

I've encountered an issue while trying to test my component unit. The problem arises when I call the product-list.component.ts from my product.service.ts. While my product.service.spec.ts is successful, the product-list.component.spec.ts fails as the ...

What is the process for importing DataTables using npm?

My attempt to import "datatables.net-select" using the usual method doesn't seem to be working. After checking the website, I found that the correct way to do it is: var $ = require( 'jquery' ); var dt = require( 'datatable ...

Setting up ESLint and Prettier with TypeScript on Node 20: A Guide

I attempted to set up Prettier with ESLint and crafted a configuration in settings.json to rectify errors upon saving, but the errors only manifest in .js files and not .ts files. How can I adjust this? Dependencies: "@eslint/js": "^9.4.0& ...

The field 'XXX' is not a valid property on the type 'CombinedVueInstance<Vue, {}, {}, {}, Readonly<Record<never, any>>>'

When creating a Vue component with TypeScript, I encountered an error message in the data() and methods() sections: Property 'xxx' does not exist on type 'CombinedVueInstance<Vue, {}, {}, {}, Readonly<Record<never, any>>>& ...

You must pass a string, Buffer, ArrayBuffer, or Array as the first argument when using Uint8Array.slice(). A number was received instead

Here is my implementation of the ByteArray class, which extends the Uint8Array class. export class ByteArray extends Uint8Array { ... private _encoded: string; ... constructor(_encoded: string) { super(Buffer.from(_encoded, " ...

The code encountered an error with message TS2345 stating that the argument type '(a: Test, b: Test) => boolean | 1' cannot be assigned to a parameter type of '(a: Test, b: Test) => number'

Apologies for the lengthy subject, but I am having trouble understanding the response. Here is my code snippet: this.rezerwacjeFilteredByseaarchInput.sort(function (a, b) { if (a[5]===null) { // console.log(a[5]); return 1; } ...

Angular 6 combined with Firebase is experiencing difficulties with routing after a successful login

After spending hours trying to fix my issue, I still can't figure it out. I've searched through related threads on SO, but haven't found a solution yet. Issue After successfully signing up, the email verification flag is set to true. Howev ...

Displaying Firebase values in an Angular 2 list is a breeze

Here is the functionality to load, add, and mark ToDo as Finished: todos: FirebaseListObservable<any>; ngOnInit(){ this.todos = this._af.database.list('todos') } addTodo(newTodo: string){ this.todos.push({ ...

The ReactJS template with Typescript is throwing an error stating that the property useContext does not exist on type

After creating a react-app using yarn create react-app app-name --template typescript, I have the following code snippets to share: AuthProvider.tsx import { createContext, useState } from "react"; const AuthContext = createContext({ }); ex ...

a guide to transforming data into a string with json using angular

I am struggling to figure out how to bind my form data into a JSON string. My situation involves using a string field in the database and saving checkbox values in a single database column using JSON. I have created an HTML form, but I am unsure of how to ...

The FormGroup Matrix in Angular 2+

Looking to develop an interface for creating a matrix, which requires two inputs for width and height. The matrix of inputs will vary based on these dimensions. I'm facing a challenge in making these inputs unique so they can be correctly associated ...

What is the best way to shorten text in Angular?

I am looking to display smaller text on my website. I have considered creating a custom pipe to truncate strings, but in my situation it's not applicable. Here's what I'm dealing with: <p [innerHTML]="aboutUs"></p> Due to t ...

The error message "Property '$store' is not defined on type 'ComponentPublicInstance' when using Vuex 4 with TypeScript" indicates that the property '$store' is not recognized

I'm currently working on a project that involves using TypeScript and Vue with Vuex. I've encountered an error in VSCode that says: Property '$store' does not exist on type 'ComponentPublicInstance<{}, {}, {}, { errors(): any; } ...

Implementing a Typescript hook using useContext along with an uninitialized context object

I am currently attempting to develop a custom hook called useAuth in React 17 with TypeScript. While my solution is somewhat functioning, it requires the following syntax when utilizing the hook methods: const auth = useAuth(); // Do other stuff ...

What is the best way to include a Generic type into a functional component's props that also extends a different interface for its props?

Explanation I am currently working on developing a dynamic input form using the FormProvider feature from react-hook-form. const formMethods = useForm<TSongFormData>(); return ( <FormProvider {...formMethods}> <SongInputForm /> ...

The alias for the computed column is not correctly connected to the TypeORM Entity

I am currently working on extracting data from a table in a MySQL database using TypeORM for my Express.js project. In order to retrieve the data, I am utilizing the QueryBuilder. This is the implementation I have: const result = await this.repository.cr ...

Having difficulty authenticating Slack requests

I'm currently working on a project to develop a Slack bot using the events API for an experiment at my job. I am facing challenges in verifying the request and can't seem to pinpoint where I'm making a mistake. The bot is being built using ...

Expressjs - Error: Headers already sent to the client and cannot be set

After testing various solutions from others, I am still unable to resolve this error. My objective is to iterate through each item in the array sourced below: novel.ts export let indexList = (req: Request, res: Response) => { novel.getAllDocuments ...

Implementing Default Language in Next.js 14 for Static Export without URL Prefix: A Step-by-Step Guide

Currently, I am in the process of developing a website using Next.js 14, with the intention of exporting it as a static site for distribution through a CDN (Cloudflare Pages). The website I am working on requires support for internationalization (i18n) to ...

The final value of a loop is consistently returned each time

Creating a loop to generate objects. Action.ts public campaing:any = { 'id': '', 'campaing_code': '', 'campaing_type': '', 'start_date': this.currentDate, 'end ...