Skip to main content
Version: 4.xx.xx
Source Code

useTable

useTable allows us to fetch data according to the sorter, filter, and pagination states. Under the hood, it uses useList for the fetch. Since it is designed to be headless, it expects you to handle the UI.

INFORMATION

If you're looking for a complete table library, Refine supports two table libraries out of the box.

Basic Usage​

In basic usage, useTable returns the data as it comes from the endpoint. By default, it reads resource from the URL.

localhost:3000/posts
import React from "react";
import { useTable, HttpError } from "@refinedev/core";

interface IPost {
id: number;
title: string;
content: string;
status: "published" | "draft" | "rejected";
createdAt: string;
}

const PostList: React.FC = () => {
const { tableQueryResult } = useTable<IPost, HttpError>();
const posts = tableQueryResult?.data?.data ?? [];

if (tableQueryResult?.isLoading) {
return <div>Loading...</div>;
}

return (
<div>
<h1>Posts</h1>
<table>
<thead>
<tr>
<th>ID</th>
<th>Title</th>
<th>Status</th>
<th>Created At</th>
</tr>
</thead>
<tbody>
{posts.map((post) => (
<tr key={post.id}>
<td>{post.id}</td>
<td>{post.title}</td>
<td>{post.status}</td>
<td>{new Date(post.createdAt).toDateString()}</td>
</tr>
))}
</tbody>
</table>
</div>
);
};

Pagination​

useTable has a pagination feature. The pagination is done by passing the current and pageSize keys to pagination object. The current is the current page, and the pageSize is the number of records per page.

It also syncs the pagination state with the URL if you enable the syncWithLocation.

By default, the current is 1 and the pageSize is 10. You can change default values by passing the pagination.current and pagination.pageSize props to the useTable hook.

You can also change the current and pageSize values by using the setCurrent and setPageSize functions that are returned by the useTable hook. Every change will trigger a new fetch.

By default, pagination happens on the server side. If you want to do pagination handling on the client side, you can pass the pagination.mode property and set it to "client". Also, you can disable the pagination by setting it to "off".

localhost:3000/posts
import React from "react";
import { useMany, useTable, HttpError } from "@refinedev/core";

interface IPost {
id: number;
title: string;
content: string;
status: "published" | "draft" | "rejected";
createdAt: string;
}

const PostList: React.FC = () => {
const {
tableQueryResult,
current,
setCurrent,
pageSize,
setPageSize,
pageCount,
} = useTable<IPost, HttpError>();

// Fetches the posts for the current page
const posts = tableQueryResult?.data?.data ?? [];
// Checks if there is a next page available
const hasNext = current < pageCount;
// Checks if there is a previous page available
const hasPrev = current > 1;

return (
<div>
<h1>Posts</h1>
<table>
<thead>
<tr>
<th>ID</th>
<th>Title</th>
<th>Status</th>
<th>Created At</th>
</tr>
</thead>
<tbody>
{tableQueryResult.data?.data.map((post) => (
<tr key={post.id}>
<td>{post.id}</td>
<td>{post.title}</td>
<td>{post.status}</td>
<td>{new Date(post.createdAt).toDateString()}</td>
</tr>
))}
</tbody>
</table>
<div
style={{
display: "flex",
gap: "1rem",
alignItems: "center",
}}
>
<div>
<button onClick={() => setCurrent(1)} disabled={!hasPrev}>
First
</button>
<button
onClick={() => setCurrent((prev) => prev - 1)}
disabled={!hasPrev}
>
Previous
</button>
<button
onClick={() => setCurrent((prev) => prev + 1)}
disabled={!hasNext}
>
Next
</button>
<button
onClick={() => setCurrent(pageCount)}
disabled={!hasNext}
>
Last
</button>
</div>
<span>
Page{" "}
<strong>
{current} of {pageCount}
</strong>
</span>
<span>
Go to page:
<input
type="number"
defaultValue={current + 1}
onChange={(e) => {
const value = e.target.value
? Number(e.target.value)
: 1;
setCurrent(value);
}}
/>
</span>
<select
value={pageSize}
onChange={(e) => {
const value = e.target.value
? Number(e.target.value)
: 10;
setPageSize(value);
}}
>
{[10, 20, 30, 40, 50].map((size) => (
<option key={size} value={size}>
Show {size}
</option>
))}
</select>
</div>
</div>
);
};

Sorting​

useTable has a sorter feature. The sorter is done by using the initial and permanent keys to sorters object. The initial is the initial sorter state, and the permanent is the permanent sorter state. These states are a CrudSorter type that contains the field and the order of the sorter.

You can change the sorters state by using the setSorters function. Every change will trigger a new fetch.

It also syncs the sorting state with the URL if you enable the syncWithLocation.

localhost:3000/posts
import React, { useMemo } from "react";
import { useMany, useTable, HttpError } from "@refinedev/core";

interface IPost {
id: number;
title: string;
content: string;
status: "published" | "draft" | "rejected";
createdAt: string;
}

const PostList: React.FC = () => {
const { tableQueryResult, sorter, setSorter } = useTable<IPost, HttpError>({
sorters: {
initial: [
{
field: "createdAt",
order: "desc",
},
],
},
});

// Fetches the posts for the current page
const posts = tableQueryResult?.data?.data ?? [];

// Gets the current sort order for the fields
const currentSorterOrders = useMemo(() => {
return {
createdAt:
sorter.find((item) => item.field === "createdAt")?.order ||
"desc",
id: sorter.find((item) => item.field === "id")?.order || "desc",
title:
sorter.find((item) => item.field === "title")?.order || "asc",
};
}, [sorter]);

const toggleSort = (field: string) => {
setSorter([
{
field,
order: currentSorterOrders[field] === "asc" ? "desc" : "asc",
},
]);
};

return (
<div>
<div
style={{
display: "flex",
gap: "1rem",
alignItems: "center",
marginBottom: "1rem",
}}
>
<button onClick={() => toggleSort("createdAt")}>
Sort date by{" "}
{currentSorterOrders["createdAt"] === "asc"
? "desc"
: "asc"}
</button>
<button onClick={() => toggleSort("id")}>
Sort id by{" "}
{currentSorterOrders["id"] === "asc" ? "desc" : "asc"}
</button>
<button onClick={() => toggleSort("title")}>
Sort title by{" "}
{currentSorterOrders["title"] === "asc" ? "desc" : "asc"}
</button>
</div>
<h1>Posts</h1>
<table>
<thead>
<tr>
<th>ID</th>
<th>Title</th>
<th>Status</th>
<th>Created At</th>
</tr>
</thead>
<tbody>
{tableQueryResult.data?.data.map((post) => (
<tr key={post.id}>
<td>{post.id}</td>
<td>{post.title}</td>
<td>{post.status}</td>
<td>{new Date(post.createdAt).toDateString()}</td>
</tr>
))}
</tbody>
</table>
</div>
);
};

Filtering​

useTable has a filter feature. The filter is done by using the initial, permanent and defaultBehavior keys to filters object. The initial is the initial filter state, and the permanent is the permanent filter state. These states are a CrudFilter type that contains the field, the operator, and the value of the filter.

You can change the filters state by using the setFilters function. Every change will trigger a new fetch.

It also syncs the filtering state with the URL if you enable the syncWithLocation.

setFilters function can work in two different behaviors; merge (default) and replace. You can set the behavior by passing it as the second parameter. You can change the default behavior with the filters.defaultBehavior prop.

INFORMATION

If you are using merge behavior and want to remove one of the filters, you should set the value to undefined or null. For or filters, you should set the value to an empty array [] to remove the filter.

localhost:3000/posts
import React, { useMemo } from "react";
import { useMany, useTable, HttpError } from "@refinedev/core";

interface IPost {
id: number;
title: string;
content: string;
status: "published" | "draft" | "rejected";
createdAt: string;
}

const PostList: React.FC = () => {
const { tableQueryResult, filters, setFilters } = useTable<
IPost,
HttpError
>();

// Fetches the posts for the current page
const posts = tableQueryResult?.data?.data ?? [];

// Gets the current filter values for the fields
const currentFilterValues = useMemo(() => {
// Filters can be a LogicalFilter or a ConditionalFilter. ConditionalFilter not have field property. So we need to filter them.
// We use flatMap for better type support.
const logicalFilters = filters.flatMap((item) =>
"field" in item ? item : [],
);

return {
title:
logicalFilters.find((item) => item.field === "title")?.value ||
"",
id: logicalFilters.find((item) => item.field === "id")?.value || "",
status:
logicalFilters.find((item) => item.field === "status")?.value ||
"",
};
}, [filters]);

return (
<div>
<div
style={{
display: "flex",
gap: "1rem",
alignItems: "center",
marginBottom: "4px",
}}
>
<input
placeholder="Search by title"
value={currentFilterValues.title}
onChange={(e) => {
setFilters([
{
field: "title",
operator: "contains",
value: !!e.currentTarget.value
? e.currentTarget.value
: undefined,
},
]);
}}
/>
<input
placeholder="Search by id"
value={currentFilterValues.id}
onChange={(e) => {
setFilters([
{
field: "id",
operator: "eq",
value: !!e.currentTarget.value
? e.currentTarget.value
: undefined,
},
]);
}}
/>

<select
value={currentFilterValues.status}
onChange={(e) =>
setFilters(
[
{
field: "status",
operator: "eq",
value: !!e.currentTarget.value
? e.currentTarget.value
: undefined,
},
],
"replace",
)
}
>
<option value="">All</option>
<option value="published">Published</option>
<option value="draft">Draft</option>
<option value="rejected">Rejected</option>
</select>
</div>
<h1>Posts</h1>
<table>
<thead>
<tr>
<th>ID</th>
<th>Title</th>
<th>Status</th>
<th>Created At</th>
</tr>
</thead>
<tbody>
{tableQueryResult.data?.data.map((post) => (
<tr key={post.id}>
<td>{post.id}</td>
<td>{post.title}</td>
<td>{post.status}</td>
<td>{new Date(post.createdAt).toDateString()}</td>
</tr>
))}
</tbody>
</table>
</div>
);
};

Realtime Updates​

CAUTION

This feature is only available if you use a Live Provider.

When the useTable hook is mounted, it will call the subscribe method from the liveProvider with some parameters such as channel, resource etc. It is useful when you want to subscribe to live updates.

For more information, refer to the liveProvider documentation β†’

Properties​

resource​

Default: It reads the resource value from the current URL.

It will be passed to the getList method from the dataProvider as parameter via the useList hook. The parameter is usually used as an API endpoint path. It all depends on how to handle the resource in the getList method. See the creating a data provider section for an example of how resources are handled.

import { useTable } from "@refinedev/core";
useTable({
resource: "categories",
});

If you have multiple resources with the same name, you can pass the identifier instead of the name of the resource. It will only be used as the main matching key for the resource, data provider methods will still work with the name of the resource defined in the <Refine/> component.

For more information, refer to the identifier of the <Refine/> component documentation β†’

dataProviderName​

If there is more than one dataProvider, you should use the dataProviderName that you will use. It is useful when you want to use a different dataProvider for a specific resource.

import { useTable } from "@refinedev/core";
useTable({
dataProviderName: "second-data-provider",
});

pagination.current​

Default: 1

Sets the initial value of the page index.

import { useTable } from "@refinedev/core";
useTable({
pagination: {
current: 2,
},
});

pagination.pageSize​

Default: 10

Sets the initial value of the page size.

import { useTable } from "@refinedev/core";
useTable({
pagination: {
pageSize: 20,
},
});

pagination.mode​

Default: "server"

It can be "off", "server" or "client".

  • "off": Pagination is disabled. All records will be fetched.
  • "client": Pagination is done on the client side. All records will be fetched and then the records will be paginated on the client side.
  • "server":: Pagination is done on the server side. Records will be fetched by using the current and pageSize values.
import { useTable } from "@refinedev/core";
useTable({
pagination: {
mode: "client",
},
});

sorters.mode​

Default: "server"

It can be "off", or "server".

  • "off": sorters do not get sent to the server. You can use the sorters value to sort the records on the client side.
  • "server":: Sorting is done on the server side. Records will be fetched by using the sorters value.
import { useTable } from "@refinedev/core";
useTable({
sorters: {
mode: "server",
},
});

sorters.initial​

Sets the initial value of the sorter. The initial is not permanent. It will be cleared when the user changes the sorter. If you want to set a permanent value, use the sorters.permanent prop.

import { useTable } from "@refinedev/core";
useTable({
sorters: {
initial: [
{
field: "name",
order: "asc",
},
],
},
});

For more information, refer to the CrudSorting interface→

sorters.permanent​

Sets the permanent value of the sorter. The permanent is permanent and unchangeable. It will not be cleared when the user changes the sorter. If you want to set a temporary value, use the sorters.initial prop.

import { useTable } from "@refinedev/core";
useTable({
sorters: {
permanent: [
{
field: "name",
order: "asc",
},
],
},
});

For more information, refer to the CrudSorting interface β†’

filters.mode​

Default: "server"

It can be "off" or "server".

  • "off": filters are not sent to the server. You can use the filters value to filter the records on the client side.
  • "server":: Filters are done on the server side. Records will be fetched by using the filters value.
import { useTable } from "@refinedev/core";
useTable({
filters: {
mode: "off",
},
});

filters.initial​

Sets the initial value of the filter. The initial is not permanent. It will be cleared when the user changes the filter. If you want to set a permanent value, use the filters.permanent prop.

import { useTable } from "@refinedev/core";
useTable({
filters: {
initial: [
{
field: "name",
operator: "contains",
value: "Foo",
},
],
},
});

For more information, refer to the CrudFilters interface β†’

filters.permanent​

Sets the permanent value of the filter. The permanent is permanent and unchangeable. It will not be cleared when the user changes the filter. If you want to set a temporary value, use the filters.initial prop.

import { useTable } from "@refinedev/core";
useTable({
filters: {
permanent: [
{
field: "name",
operator: "contains",
value: "Foo",
},
],
},
});

For more information, refer to the CrudFilters interface β†’

filters.defaultBehavior​

Default: merge

The filtering behavior can be set to either "merge" or "replace".

  • When the filter behavior is set to "merge", it will merge the new filter with the existing filters. This means that if the new filter has the same column as an existing filter, the new filter will replace the existing filter for that column. If the new filter has a different column than the existing filters, it will be added to the existing filters.

  • When the filter behavior is set to "replace", it will replace all existing filters with the new filter. This means that any existing filters will be removed, and only the new filter will be applied to the table.

You can also override the default value by using the second parameter of the setFilters function.

import { useTable } from "@refinedev/core";
useTable({
filters: {
defaultBehavior: "replace",
},
});

syncWithLocation​

Default: false

When you use the syncWithLocation feature, the useTable's state (e.g., sort order, filters, pagination) is automatically encoded in the query parameters of the URL, and when the URL changes, the useTable state is automatically updated to match. This makes it easy to share table state across different routes or pages, and to allow users to bookmark or share links to specific table views.

Also, you can set this value globally on <Refine> component.

import { useTable } from "@refinedev/core";
useTable({
syncWithLocation: true,
});

queryOptions​

useTable uses useList hook to fetch data. You can pass queryOptions.

import { useTable } from "@refinedev/core";
useTable({
queryOptions: {
retry: 3,
},
});

meta​

meta is a special property that can be used to pass additional information to data provider methods for the following purposes:

  • Customizing the data provider methods for specific use cases.
  • Generating GraphQL queries using plain JavaScript Objects (JSON).

In the following example, we pass the headers property in the meta object to the create method. With similar logic, you can pass any properties to specifically handle the data provider methods.

import { useTable } from "@refinedev/core";
useTable({
meta: {
headers: { "x-meta-data": "true" },
},
});

const myDataProvider = {
//...
getList: async ({
resource,
pagination,
sorters,
filters,
meta,
}) => {
const headers = meta?.headers ?? {};
const url = `${apiUrl}/${resource}`;

//...
//...

const { data, headers } = await httpClient.get(`${url}`, { headers });

return {
data,
};
},
//...
};

For more information, refer to the meta section of the General Concepts documentation→

successNotification​

CAUTION

NotificationProvider is required for this prop to work.

After data is fetched successfully, useTable can call open function from NotificationProvider to show a success notification. With this prop, you can customize the success notification.

import { useTable } from "@refinedev/core";
useTable({
successNotification: (data, values, resource) => {
return {
message: `${data.title} Successfully fetched.`,
description: "Success with no errors",
type: "success",
};
},
});

errorNotification​

CAUTION

NotificationProvider is required for this prop to work.

After data fetching is failed, useTable will call open function from NotificationProvider to show an error notification. With this prop, you can customize the error notification.

import { useTable } from "@refinedev/core";
useTable({
errorNotification: (data, values, resource) => {
return {
message: `Something went wrong when getting ${data.id}`,
description: "Error",
type: "error",
};
},
});

liveMode​

CAUTION

LiveProvider is required for this prop to work.

Determines whether to update data automatically ("auto") or not ("manual") if a related live event is received. It can be used to update and show data in Realtime throughout your app.

import { useTable } from "@refinedev/core";
useTable({
liveMode: "auto",
});

For more information, refer to the Live / Realtime page

onLiveEvent​

CAUTION

LiveProvider is required for this prop to work.

The callback function is executed when new events from a subscription have arrived.

import { useTable } from "@refinedev/core";
useTable({
onLiveEvent: (event) => {
console.log(event);
},
});

liveParams​

CAUTION

LiveProvider is required for this prop to work.

Params to pass to liveProvider's subscribe method.

overtimeOptions​

If you want loading overtime for the request, you can pass the overtimeOptions prop to the this hook. It is useful when you want to show a loading indicator when the request takes too long. interval is the time interval in milliseconds. onInterval is the function that will be called on each interval.

Return overtime object from this hook. elapsedTime is the elapsed time in milliseconds. It becomes undefined when the request is completed.

import { useTable } from "@refinedev/core";
const { overtime } = useTable({
//...
overtimeOptions: {
interval: 1000,
onInterval(elapsedInterval) {
console.log(elapsedInterval);
},
},
});

console.log(overtime.elapsedTime); // undefined, 1000, 2000, 3000 4000, ...

// You can use it like this:
{
elapsedTime >= 4000 && <div>this takes a bit longer than expected</div>;
}

initialCurrent​

Deprecated

Use pagination.current instead.

Default: 1

Sets the initial value of the page index.

import { useTable } from "@refinedev/core";
useTable({
initialCurrent: 2, // This will cause the table to initially display the data for page 2, rather than the default of page 1
});

initialPageSize​

Deprecated

Use pagination.pageSize instead.

Default: 10

Sets the initial value of the page size.

import { useTable } from "@refinedev/core";
useTable({
initialPageSize: 20, // This will cause the table to initially display 20 rows per page, rather than the default of 10
});

hasPagination​

Deprecated

Use pagination.mode instead.

Default: true

Determines whether to use server-side pagination or not.

import { useTable } from "@refinedev/core";
useTable({
hasPagination: false,
});

initialSorter​

Deprecated

Use sorters.initial instead.

Sets the initial value of the sorter. The initialSorter is not permanent. It will be cleared when the user changes the sorter. If you want to set a permanent value, use the permanentSorter prop.

Refer to the CrudSorting interface for more information β†’

import { useTable } from "@refinedev/core";
useTable({
initialSorter: [
{
field: "name",
order: "asc",
},
],
});

permanentSorter​

Deprecated

Use sorters.permanent instead.

Sets the permanent value of the sorter. The permanentSorter is permanent and unchangeable. It will not be cleared when the user changes the sorter. If you want to set a temporary value, use the initialSorter prop.

import { useTable } from "@refinedev/core";
useTable({
permanentSorter: [
{
field: "name",
order: "asc",
},
],
});

For more information, refer to the CrudSorting interface β†’

initialFilter​

Deprecated

Use filters.initial instead.

Sets the initial value of the filter. The initialFilter is not permanent. It will be cleared when the user changes the filter. If you want to set a permanent value, use the permanentFilter prop.

import { useTable } from "@refinedev/core";
useTable({
initialFilter: [
{
field: "name",
operator: "contains",
value: "Foo",
},
],
});

For more information, refer to the CrudFilters interface β†’

permanentFilter​

Deprecated

Use filters.permanent instead.

Sets the permanent value of the filter. The permanentFilter is permanent and unchangeable. It will not be cleared when the user changes the filter. If you want to set a temporary value, use the initialFilter prop.

import { useTable } from "@refinedev/core";
useTable({
permanentFilter: [
{
field: "name",
operator: "contains",
value: "Foo",
},
],
});

For more information, refer to the CrudFilters interface β†’

defaultSetFilterBehavior​

Deprecated

Use filters.defaultBehavior instead.

Default: merge

The filtering behavior can be set to either "merge" or "replace".

  • When the filter behavior is set to "merge", it will merge the new filter with the existing filters. This means that if the new filter has the same column as an existing filter, the new filter will replace the existing filter for that column. If the new filter has a different column than the existing filters, it will be added to the existing filters.

  • When the filter behavior is set to "replace", it will replace all existing filters with the new filter. This means that any existing filters will be removed, and only the new filter will be applied to the table.

You can also override the default value by using the second parameter of the setFilters function.

import { useTable } from "@refinedev/core";
useTable({
defaultSetFilterBehavior: "replace",
});

Return Values​

tableQueryResult​

Returned values from useList hook.

sorters​

Current sorters state.

setSorters​

A function to set current sorters state.

 (sorters: CrudSorting) => void;

filters​

Current filters state.

setFilters​

((filters: CrudFilters, behavior?: SetFilterBehavior) => void) & ((setter: (prevFilters: CrudFilters) => CrudFilters) => void)

A function to set current filters state.

current​

Current page index state. If pagination is disabled, it will be undefined.

setCurrent​

React.Dispatch<React.SetStateAction<number>> | undefined;

A function to set the current page index state. If pagination is disabled, it will be undefined.

pageSize​

Current page size state. If pagination is disabled, it will be undefined.

setPageSize​

React.Dispatch<React.SetStateAction<number>> | undefined;

A function to set the current page size state. If pagination is disabled, it will be undefined.

pageCount​

Total page count state. If pagination is disabled, it will be undefined.

createLinkForSyncWithLocation​

(params: SyncWithLocationParams) => string;

A function creates accessible links for syncWithLocation. It takes SyncWithLocationParams as parameters.

overtime​

overtime object is returned from this hook. elapsedTime is the elapsed time in milliseconds. It becomes undefined when the request is completed.

import { useTable } from "@refinedev/core";
const { overtime } = useTable();

console.log(overtime.elapsedTime); // undefined, 1000, 2000, 3000 4000, ...

sorter​

Deprecated

Use sorters instead.

Current sorters state.

setSorter​

Deprecated

Use setSorters instead.

A function to set current sorters state.

 (sorters: CrudSorting) => void;

FAQ​

How can I handle relational data?​

You can use useMany hook to fetch relational data.

localhost:3000/posts
import React from "react";
import {
useTable,
useMany,
HttpError,
} from "@refinedev/core";

interface ICategory {
id: number;
title: string;
}

interface IPost {
id: number;
title: string;
content: string;
status: "published" | "draft" | "rejected";
createdAt: string;
category: {
id: number;
};
}

const PostList: React.FC = () => {
const { tableQueryResult } = useTable<IPost, HttpError>();
const posts = tableQueryResult?.data?.data ?? [];

// Fetches the category of each post. It uses the useMany hook to fetch the category data from the API.
const { data: categoryData, isLoading: categoryIsLoading } = useMany<
ICategory,
HttpError
>({
resource: "categories",
// Creates the array of ids. This will filter and fetch the category data for the relevant posts.
ids: posts.map((item) => item?.category?.id),
queryOptions: {
// Set to true only if the posts array is not empty.
enabled: !!posts.length,
},
});

if (tableQueryResult?.isLoading) {
return <div>Loading...</div>;
}

return (
<div>
<h1>Posts</h1>
<table>
<thead>
<tr>
<th>ID</th>
<th>Title</th>
<th>Status</th>
<th>Created At</th>
<th>Category</th>
</tr>
</thead>
<tbody>
{posts.map((post) => (
<tr key={post.id}>
<td>{post.id}</td>
<td>{post.title}</td>
<td>{post.status}</td>
<td>{new Date(post.createdAt).toDateString()}</td>
<td>
{categoryIsLoading
? "loading..."
: // Gets the title of the category from the categoryData object, which is the result of the useMany hook.
categoryData?.data.find(
(item) =>
item.id === post.category.id,
)?.title || "-"}
</td>
</tr>
))}
</tbody>
</table>
</div>
);
};

How can I handle client side filtering?​

First, you need to set filters.mode: "off"

import { useTable } from "@refinedev/core";
const { tableQueryResult, filters, setFilters } = useTable({
filters: {
mode: "off",
},
});

Then, you can use the filters state to filter your data.

// ...

const List = () => {
const { tableQueryResult, filters } = useTable();

// ...

const filteredData = useMemo(() => {
if (filters.length === 0) {
return tableQueryResult.data;
}

// Filters can be a LogicalFilter or a ConditionalFilter. ConditionalFilter not have field property. So we need to filter them.
// We use flatMap for better type support.
const logicalFilters = filters.flatMap((item) => ("field" in item ? item : []));

return tableProps.dataSource.filter((item) => {
return logicalFilters.some((filter) => {
if (filter.operator === "eq") {
return item[filter.field] === filter.value;
}
});
});
}, [tableQueryResult.data, filters]);
};

return (
<div>
{/* ... */}
<table>
<tbody>
{filteredData.map((item) => (
<tr key={item.id}>{/* ... */}</tr>
))}
</tbody>
</table>
</div>
);

How can I handle client side sorting?​

First, you need to set sorters.mode: "off"

import { useTable } from "@refinedev/core";
const { tableQueryResult, sorters, setSorters } = useTable({
sorters: {
mode: "off",
},
});

Then, you can use the sorters state to sort your data.

// ...
import { useTable } from "@refinedev/core";
const List = () => {
const { tableQueryResult, sorters } = useTable();

// ...

const sortedData = useMemo(() => {
if (sorters.length === 0) {
return tableQueryResult.data;
}

return tableQueryResult.data.sort((a, b) => {
const sorter = sorters[0];

if (sorter.order === "asc") {
return a[sorter.field] > b[sorter.field] ? 1 : -1;
} else {
return a[sorter.field] < b[sorter.field] ? 1 : -1;
}
});
}, [tableQueryResult.data, sorters]);

return (
<div>
{/* ... */}
<table>
<tbody>
{sortedData.map((item) => (
<tr key={item.id}>{/* ... */}</tr>
))}
</tbody>
</table>
</div>
);
};

API​

Properties​

Type Parameters​

PropertyDescriptionTypeDefault
TQueryFnDataResult data returned by the query function. Extends BaseRecordBaseRecordBaseRecord
TErrorCustom error object that extends HttpErrorHttpErrorHttpError
TSearchVariablesValues for search params{}
TDataResult data returned by the select function. Extends BaseRecord. If not specified, the value of TQueryFnData will be used as the default value.BaseRecordTQueryFnData

Return values​

PropertyDescriptionType
tableQueryResultResult of the react-query's useQueryQueryObserverResult<{`` data: TData[];`` total: number; },`` TError>
currentCurrent page index state (returns undefined if pagination is disabled)number | undefined
pageCountTotal page count (returns undefined if pagination is disabled)number | undefined
setCurrentA function that changes the current (returns undefined if pagination is disabled)React.Dispatch<React.SetStateAction<number>> | undefined
pageSizeCurrent pageSize state (returns undefined if pagination is disabled)number | undefined
setPageSizeA function that changes the pageSize. (returns undefined if pagination is disabled)React.Dispatch<React.SetStateAction<number>> | undefined
sortersCurrent sorting statesCrudSorting
setSortersA function that accepts a new sorters state.(sorters: CrudSorting) => void
sorterCurrent sorting statesCrudSorting
setSorterA function that accepts a new sorters state.(sorters: CrudSorting) => void
filtersCurrent filters stateCrudFilters
setFiltersA function that accepts a new filter state- (filters: CrudFilters, behavior?: "merge" \| "replace" = "merge") => void - (setter: (previousFilters: CrudFilters) => CrudFilters) => void
createLinkForSyncWithLocationA function create accessible links for syncWithLocation(params: SyncWithLocationParams) => string;
overtimeOvertime loading props{ elapsedTime?: number }