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?