How can I setCacheData so that when pageSize changes, the list updates correctly in Reactjs?

February 6, 2026 -- views • -- viewers

Initially, before I clicked and filled in the HotTable cells, the cacheData was empty. However, when I changed the pagesize, it displayed the correct amount of data according to the adjusted pagesize (thanks to RowDataClean). But when I clicked on that data cell in the HotTable, the cacheData now contained data. And when I changed the pagesize to 50 or 100, it displayed the wrong amount of data.

image.png
const rowDataClean = React.useMemo(() => {
    if (!listPending) return [];
  
    return listPending.map(item => ({
      ...item,
     
      procurement_feed_backs: item.procurement_feed_backs
        ? item.procurement_feed_backs.map(fb => ({
          ...fb,
     
        }))
        : []
    }));
  }, [listPending]);
const displayData = useMemo(() => {
    console.log("cachedData[currentPage] = " + cachedData[currentPage]?.length)
    console.log("rowDataClean = " + rowDataClean.length)
    // return rowDataClean;
    return cachedData[currentPage] || rowDataClean;
  }, [currentPage, rowDataClean]);
 <TablePagination
                component="div"
                count={metadata.totalCount || 0}
                page={currentPage - 1}
                onPageChange={handleOnPageChange}
                rowsPerPage={rowsPerPage}
                onRowsPerPageChange={handleChangeRowsPerPage}
                rowsPerPageOptions={[25, 50, 100, 200]}
                labelDisplayedRows={() => null}
                sx={{
                  borderBottom: 'none',
                  '.MuiTablePagination-actions': { display: 'none' },
                  '.MuiTablePagination-spacer': { display: 'none' },
                }}
              />
<HotTable
          ref={hotRef}
          data={displayData}
          columns={hotColumns}
          licenseKey="non-commercial-and-evaluation"
          copyPaste={true}
          beforePaste={handleBeforeCopyPaste} // 1
          multiSelect={true}
          search={true}
          afterChange={handleAfterChange} //2

          width="100%"
          rowHeaders={true}
          colHeaders={true}
          autoWrapRow={true}
          height={900}
          autoWrapCol={true}
          renderAllRows={false}
          viewportRowRenderingOffset={20}
          pagination={false}
          fillHandle={
            {
              direction: 'vertical',
              autoInsertRow: true
            }

          }
          // 3
          beforeKeyDown={(event) => {
            const hotInstance = hotRef.current.hotInstance;
            if (!hotInstance || !hotInstance.getSelected()) return;

            const selection = hotInstance.getSelectedRangeLast();
            const colProp = hotInstance.colToProp(selection.highlight.col);

            if (colProp === 'procurement_feed_backs.0.est_date_feedback') {
              const isCtrlPressed = event.ctrlKey || event.metaKey;
              console.log("isCtrlPressed = ", isCtrlPressed)
              if (isCtrlPressed && (event.key === 'c' || event.key === 'v' || event.key === 'x' || event.key === 'a')) {

                console.log("Đang vào 3...")
                return;
              }
              const allowedKeys = ['Backspace', 'Delete', 'ArrowLeft', 'ArrowRight', 'Tab', 'Enter'];
              if (!allowedKeys.includes(event.key) && !/^[0-9\/]$/.test(event.key)) {
                // console.log("Đang vào 1....")
                event.stopImmediatePropagation();
                event.preventDefault();
              }
              if (/^[0-9\/]$/.test(event.key)) {
                // console.log("Đang vào 2....")
                event.stopImmediatePropagation();
                event.preventDefault();
              }
              // console.log("Đang vào 4....")
            }
          }}
          //4
          afterOnCellMouseDown={(event, coords, TD) => {
            if (coords.row < 0) return;
            const colProp = hotColumns[coords.col].data;
            if (colProp === 'procurement_feed_backs.0.attached_file') {
              const target = event.target;
              const hotInstance = hotRef.current.hotInstance;
              if (target.classList.contains('view-files-trigger')) {
                const value = hotInstance.getDataAtRowProp(coords.row, colProp);
                if (value && value.length > 0) {
                  const rect = TD.getBoundingClientRect();
                  setHoverPopup({
                    show: true,
                    x: rect.left + window.scrollX,
                    y: rect.top + window.scrollY - 100,
                    files: Array.isArray(value) ? value : [value],
                    row: coords.row,
                    prop: colProp
                  });
                  return;
                }
              }
              if (target.classList.contains('add-file-trigger') || target === TD || TD.contains(target)) {
                const value = hotInstance.getDataAtRowProp(coords.row, colProp);
                if (!value || value.length === 0 || target.classList.contains('add-file-trigger')) {
                  setCurrentUpload({ row: coords.row, prop: colProp });
                  openFileSelector();
                  setHoverPopup(prev => ({ ...prev, show: false }));
                  return;
                }
              }
            } else {
              setHoverPopup(prev => ({ ...prev, show: false }));
            }
          }}
          //5
          afterPageSizeChange={handlePageSizeChange}
          observeChanges={false}
          contextMenu={true}
          stretchH="all"
          dragToScroll={true}
          autoColumnSize={{ allowSampleDuplicates: true, }}
          autoRowSize={false}
          outsideClickDeselects={false}
          rowHeights={13}
          viewportColumnRenderingOffset={10}
          manualRowResize={false}
          manualColumnResize={true}
          wordWrap={false}
          // handlePageNumberChange={handlePageNumberChange}
          afterPageChange={updatePaginationState} //6
        />

Respect
--

Your displayData prioritizes cachedData[currentPage] over rowDataClean. The problem is when you click cells,handleAfterChange writes into cachedData, and that cached entry never gets cleared on pageSize change. So when you switch from 25 → 50 rows, the API returns 50 rows into rowDataClean, but the stale 25-row cache wins because it's truthy.

Add setCachedData({}) inside your handleChangeRowsPerPage before fetching new data. That forces it to fall back to the fresh rowDataClean until the user interacts again.

Clear cachedData whenever rowsPerPage changes:

const handleChangeRowsPerPage = (event) => {
  const newSize = parseInt(event.target.value, 10);
  setRowsPerPage(newSize);
  setCurrentPage(1);
  setCachedData({}); // ← this is the missing line
  // ...fetch new data
};
Respect
--
End of thread

Search

Posts Tags Apps

Start typing to search across everything

Navigate Open Esc Close