Search code examples
reactjsmaterial-uimui-x-data-grid

Mui DataGrid with issues displaying items on the second page and forward


When retrieving data with specified item amounts and offsets, a display issue occurs on the second page and subsequent pages.

For instance, on the first page, the data correctly shows the first 10 items. However, when using pagination to access the next set of items, only a different number of items is returned, despite the data fetched containing 10 items in the array:

https://codesandbox.io/s/listing-pokemon-on-datagrid-76w3v5

Fetching function:

const fetchPokemon = async (limit, offset) => {
  const response = await fetch(
    `https://pokeapi.co/api/v2/pokemon?limit=${limit}&offset=${offset}`
  );
  const data = await response.json();

  // this returns 10 items
  console.log(data);

  const returnedValues = {
    results: data.results,
    count: data.count
  };

  return returnedValues;
};

DataGrid component:

<DataGrid
    autoHeight
    columns={cols}
    loading={dataGridState.loading}
    rowCount={dataGridState.amount}
    rows={pokemon}
    pagination={{
      pageSize: dataGridState.pageSize,
      page: dataGridState.offset - 1
    }}
    pageSize={dataGridState.pageSize}
    onPageChange={handlePageSize}
    onPaginationModelChange={async (val) => handlePageSize(val)}
  />

enter image description here


Solution

  • You are using server-side pagination, which means you are fetching the data from a remote source and handling the pagination logic on the server. So you need to pass the paginationMode prop with the value server to the DataGrid component. This tells the component that it should not handle the pagination internally, but delegate it to the server.

    For example:

    <DataGrid
      {...restProps}
      paginationMode="server"
    />
    

    You can see the whole example here: codesandbox.io.

    To learn more, please see Server Side Pagination Docs.

    According to this documentation:

    • Set the prop paginationMode to server
    • Provide a rowCount prop to let the data grid know how many pages there are
    • Use the onPaginationModelChange prop callback to load the rows when the page changes

    PS: You're using dataGridState.offset as page. It's wrong. Instead, you need to use dataGridState.offset / dataGridState.pageSize + 1 as page.