Skip to content

[BUG] with useDataGrid and SSR, page can reset to 0 when paging #6798

Description

@rkmackinnon

Describe the bug

When using SSR with NextJS and Mui, the rowCount prop provided by useDataGrid can sometimes become undefined during loading. This resets the current page to zero. The callout here: https://mui.com/x/react-data-grid/pagination/#server-side-pagination describes the problem and an easy solution.

Steps To Reproduce

  1. Set up a project with next, @refinedev/mui and @refinedev/nextjs-router
  2. Enable SSR with getServerSideProps
  3. Call useDataGrid with pagination options
  4. Change pages
  5. Try it a few times. It doesn't happen every time, but it happens frequently enough that it should take only seconds to reproduce.

Expected behavior

The page does not reset to zero when paging.

Packages

  • @refinedev/cli: 2.16.42
  • @refinedev/core: 4.57.5
  • @refinedev/devtools: 1.2.12
  • @refinedev/inferencer: 5.0.3
  • @refinedev/kbar: 1.3.14
  • @refinedev/mui: 5.22.0
  • @refinedev/nextjs-router: 6.2.3
  • @refinedev/react-hook-form: 4.9.3

Note, however, that the latest @refinedev/mui: 6.1.3 as of the time of this writing most likely also has this problem, as the rowCount is not memoized there either.

Additional Context

This patch for @refinedev/mui 5.22.0 fixes the problem for me.

diff --git a/src/hooks/useDataGrid/index.ts b/src/hooks/useDataGrid/index.ts
index 1b37a5686f406301020d829e00ca50bb6410cd69..4123354250877cffc8b5cc0698d5d1731355e16d 100644
--- a/src/hooks/useDataGrid/index.ts
+++ b/src/hooks/useDataGrid/index.ts
@@ -13,7 +13,7 @@ import {
   type useTableReturnType as useTableReturnTypeCore,
   useResourceParams,
 } from "@refinedev/core";
-import { useState } from "react";
+import { useMemo, useRef, useState } from "react";
 
 import type {
   DataGridProps,
@@ -215,6 +215,14 @@ export function useDataGrid<
 
   const { data, isFetched, isLoading } = tableQueryResult;
 
+  const rowCountRef = useRef(data?.total || 0);
+  const rowCount = useMemo(() => {
+    if (data && data.total) {
+      rowCountRef.current = data.total;
+    }
+    return rowCountRef.current;
+  }, [data]);
+
   const isServerSideFilteringEnabled =
     (filtersFromProp?.mode || "server") === "server";
   const isServerSideSortingEnabled =
@@ -327,7 +335,7 @@ export function useDataGrid<
       disableRowSelectionOnClick: true,
       rows: data?.data || [],
       loading: liveMode === "auto" ? isLoading : !isFetched,
-      rowCount: data?.total || 0,
+      rowCount,
       ...dataGridPaginationValues(),
       sortingMode: isServerSideSortingEnabled ? "server" : "client",
       sortModel: transformCrudSortingToSortModel(

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions