# Server-side
Package: @mantine/data-grid
Import: import { DataGridServerSide } from '@mantine/data-grid';
Description: DataGrid server-side sorting, filtering, pagination

## Overview

Use server-side mode when the dataset is too large to load in the browser, or when sorting,
filtering and pagination are handled by an API. Set the `manual*` options and pass controlled
state to `useDataGrid`.

## Server-side sorting

Set `manualSorting` to disable client-side sorting. Use controlled `sorting` and
`onSortingChange` to send the sort state to your API:

```tsx
const store = useDataGrid({
  data: serverData,
  columns,
  manualSorting: true,
  sorting,
  onSortingChange: setSorting,
});
```

## Server-side filtering

Set `manualFiltering` to disable client-side filtering. Use controlled `columnFilters`
and `onColumnFiltersChange` to send the filter state to your API. The grid renders no filter
inputs in this mode, bind your own controls to the store filter methods, see [Filtering](https://alpha.mantine.dev/llms/data-grid-filtering.md):

```tsx
const store = useDataGrid({
  data: serverData,
  columns,
  withFiltering: true,
  manualFiltering: true,
  columnFilters,
  onColumnFiltersChange: setColumnFilters,
});
```

## Server-side pagination

Set `manualPagination` and provide `rowCount` with the total number of rows. `DataGrid.Footer`
uses it to display the `1–10 of 200` range and the page count:

```tsx
const store = useDataGrid({
  data: serverData,
  columns,
  manualPagination: true,
  pagination,
  onPaginationChange: setPagination,
  rowCount: totalRowCount,
});
```

## Full example

Server-side sorting, filtering and pagination with a simulated API delay. With
`loadingVariant="bar"`, the current rows stay visible while the next page is fetched.
See [States](https://alpha.mantine.dev/llms/data-grid-states.md) for the other loading variants:

```tsx
import { useCallback, useEffect, useMemo, useState } from 'react';
import { ColumnFiltersState, PaginationState, SortingState } from '@tanstack/react-table';
import { Select, TextInput } from '@mantine/core';
import { DataGrid, useDataGrid } from '@mantine/data-grid';

interface ServerRow {
  id: string;
  name: string;
  email: string;
  department: string;
  salary: number;
}

const departments = ['Engineering', 'Marketing', 'Sales', 'HR', 'Finance'];

const allData: ServerRow[] = Array.from({ length: 200 }, (_, i) => ({
  id: String(i + 1),
  name: `Employee ${i + 1}`,
  email: `employee${i + 1}@example.com`,
  department: departments[i % departments.length],
  salary: 50000 + (i * 500),
}));

function fetchServerData(params: {
  sorting: SortingState;
  columnFilters: ColumnFiltersState;
  pagination: PaginationState;
}): Promise<{ data: ServerRow[]; totalCount: number }> {
  return new Promise((resolve) => {
    setTimeout(() => {
      let filtered = [...allData];

      params.columnFilters.forEach((filter) => {
        const value = String(filter.value).toLowerCase();
        filtered = filtered.filter((row) =>
          String(row[filter.id as keyof ServerRow]).toLowerCase().includes(value)
        );
      });

      if (params.sorting.length > 0) {
        const { id, desc } = params.sorting[0];
        filtered.sort((a, b) => {
          const aVal = a[id as keyof ServerRow];
          const bVal = b[id as keyof ServerRow];
          if (aVal < bVal) {
            return desc ? 1 : -1;
          }
          if (aVal > bVal) {
            return desc ? -1 : 1;
          }
          return 0;
        });
      }

      const totalCount = filtered.length;
      const { pageIndex, pageSize } = params.pagination;
      const start = pageIndex * pageSize;
      const paged = filtered.slice(start, start + pageSize);

      resolve({ data: paged, totalCount });
    }, 500);
  });
}

function Demo() {
  const [data, setData] = useState<ServerRow[]>([]);
  const [loading, setLoading] = useState(true);
  const [totalCount, setTotalCount] = useState(0);
  const [sorting, setSorting] = useState<SortingState>([]);
  const [columnFilters, setColumnFilters] = useState<ColumnFiltersState>([]);
  const [pagination, setPagination] = useState<PaginationState>({
    pageIndex: 0,
    pageSize: 10,
  });

  const fetchData = useCallback(() => {
    setLoading(true);
    fetchServerData({ sorting, columnFilters, pagination }).then((result) => {
      setData(result.data);
      setTotalCount(result.totalCount);
      setLoading(false);
    });
  }, [sorting, columnFilters, pagination]);

  useEffect(() => {
    fetchData();
  }, [fetchData]);

  const columns = useMemo(
    () => [
      { accessorKey: 'id' as const, header: 'ID', size: 80, enableColumnFilter: true },
      { accessorKey: 'name' as const, header: 'Name', enableSorting: true, enableColumnFilter: true },
      { accessorKey: 'email' as const, header: 'Email', size: 220, enableSorting: true, enableColumnFilter: true },
      { accessorKey: 'department' as const, header: 'Department', enableSorting: true, enableColumnFilter: true },
      { accessorKey: 'salary' as const, header: 'Salary', enableSorting: true, enableColumnFilter: true },
    ],
    []
  );

  const store = useDataGrid({
    data,
    columns,
    manualSorting: true,
    sorting,
    onSortingChange: setSorting,
    manualFiltering: true,
    columnFilters,
    onColumnFiltersChange: (updater) => {
      setColumnFilters(updater);
      setPagination((current) => ({ ...current, pageIndex: 0 }));
    },
    manualPagination: true,
    pagination,
    onPaginationChange: setPagination,
    rowCount: totalCount,
  });

  return (
    <DataGrid store={store} loading={loading} loadingVariant="bar">
      <DataGrid.Toolbar>
        <TextInput
          size={store.getControlSize()}
          placeholder="Filter by name"
          value={(store.getColumnFilterValue('name') as string) ?? ''}
          onChange={(event) => store.setColumnFilter('name', event.currentTarget.value)}
        />
        <Select
          size={store.getControlSize()}
          placeholder="Any department"
          clearable
          data={departments}
          value={(store.getColumnFilterValue('department') as string) ?? null}
          onChange={(value) => store.setColumnFilter('department', value)}
        />
      </DataGrid.Toolbar>
      <DataGrid.Footer />
    </DataGrid>
  );
}
```


## Server-side grouping

Set `manualGrouping` in `tableOptions` to disable client-side grouping. Use controlled
`grouping` and `onGroupingChange` to send the grouping state to your API:

```tsx
const store = useDataGrid({
  data: serverData,
  columns,
  withGrouping: true,
  grouping,
  onGroupingChange,
  tableOptions: { manualGrouping: true },
});
```

## Debounced filtering

Debounce the filter value to avoid sending a request on every keystroke:

```tsx
import { useEffect, useState } from 'react';
import { useDebouncedValue } from '@mantine/hooks';

const [filter, setFilter] = useState('');
const [debouncedFilter] = useDebouncedValue(filter, 300);

// Use debouncedFilter in your API call
useEffect(() => {
  fetchData({ filter: debouncedFilter });
}, [debouncedFilter]);
```

## Stable row IDs

Always provide `getRowId` when server-side pagination is used together with row selection.
Without it, selection is keyed by row index and breaks when the page changes:

```tsx
const store = useDataGrid({
  data: serverData,
  columns,
  manualPagination: true,
  withRowSelection: true,
  getRowId: (row) => row.id,
  rowCount: totalRowCount,
});
```

## Filter options from the API

With server-side filtering, `withFaceting` only sees the current page. Get the available filter
values from your API and pass them to your own filter controls, for example a `Select` in the toolbar:

```tsx
<DataGrid store={store}>
  <DataGrid.Toolbar>
    <Select
      size={store.getControlSize()}
      placeholder="Department"
      clearable
      data={facets.department}
      value={(store.getColumnFilterValue('department') as string) ?? null}
      onChange={(value) => store.setColumnFilter('department', value)}
    />
  </DataGrid.Toolbar>
</DataGrid>
```

## Empty results

The `emptyState` payload reports `rowCount` from the `rowCount` option, so a server-side grid can
tell an empty data source from an empty page of results, see [States](https://alpha.mantine.dev/llms/data-grid-states.md).
