Search code examples
material-uireact-typescript

MUI React Table Pagination: appends the next page's content instead of properly paging


The main code:

  handleChangePage(event: unknown, newPage: number) {
     this.setState({page: newPage});
  };
 
   handleChangeRowsPerPage(event: React.ChangeEvent<HTMLInputElement>) {
     this.setState({rowsPerPage: +event.target.value, page: 0});
   };
...
              <TableBody>
                {this.state.datas
        .slice(this.state.page * this.state.rowsPerPage, this.state.page * this.state.rowsPerPage + this.state.rowsPerPage - 1)
        .map((row: any) => {
          var isDiff = row.data[1].startsWith("...");
          return (
                    <StyledTableRow key={row.data[0]} sx={{ "&:last-child td, &:last-child th": { border: 0 } }}
             onClick={() => this.setState({selectedRow: row.dataIx}) }>
                  {row.data.map((cell: any) => (
                        <StyledTableCell key={cell} align="center" style={prepareDiff(isDiff, cell)}>{cell}</StyledTableCell>
                  ))}
                    </StyledTableRow>)
                })}
                {this.state.emptyRows > 0 && (
                  <StyledTableRow style={{ height: 34 * this.state.emptyRows }}>
                    <StyledTableCell colSpan={3} />
                  </StyledTableRow>
                )}
              </TableBody>
            </Table>
      </TableContainer>
          <TablePagination
            rowsPerPageOptions={[9, 18, 27, 36]}
            component="div"
            count={this.state.rows}
            rowsPerPage={this.state.rowsPerPage}
            page={this.state.page}
            onPageChange={this.handleChangePage}
            onRowsPerPageChange={this.handleChangeRowsPerPage}
          />

Main issue: when I trigger the page change, the next page's rows get appended after the old ones and they also get scrambled instead of just switching the page properly.

How can I trigger a proper refresh? Is the iterator key broken here?


Solution

  • Simply using key="" solves the paging issue. Most probably not optimal though.