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

useSimpleList

By using useSimpleList, you can get properties that are compatible with the Ant Design's <List> component. All features such as sorting, filtering, and pagination come out of the box. useSimpleList uses useTable under the hood for the fetch.

For all the other features, you can refer to the Ant Design's <List> documentation.

Usage

In the following example, we will show how to use useSimpleList to list the products.

It returns listProps which is compatible with the Ant Design's <List> component. By default, it reads the resource from the current URL.

localhost:3000/products
import { useSimpleList } from "@refinedev/antd";
import { Typography, List } from "antd";

const { Text } = Typography;

interface IProduct {
id: number;
name: string;
description: string;
price: string;
}

const ProductList: React.FC = () => {
const { listProps } = useSimpleList<IProduct>();

return <List {...listProps} renderItem={renderItem} />;
};

const renderItem = (item: IProduct) => {
const { id, name, description, price } = item;

return (
<List.Item actions={[<Text key={id}>{price}</Text>]}>
<List.Item.Meta title={name} description={description} />
</List.Item>
);
};

Pagination

This feature comes out of the box with the listProps.pagination. It generates the pagination links for the <List> component instead of react state and overrides <List>'s pagination.itemRender value.

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

If you want to make a change in the pagination of the <List>. You should pass the pagination object of the listProps to the pagination property of the <List> as below. You can override the values of the pagination object as your need.

// ...
const { listProps } = useSimpleList<IProduct>();

// ...

return (
<AntdList
{...listProps}
renderItem={renderItem}
pagination={{
...listProps.pagination,
position: "top",
size: "small",
}}
/>
);
Implementation Tips:

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". You can also disable the pagination by setting it to "off".

Sorting

The useSimpleList hook supports the sorting feature. You can pass the sorters property to the hook to set the initial and permanent sorting state.

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

localhost:3000/products
import { useSimpleList } from "@refinedev/antd";
import { Typography, List } from "antd";

const { Text } = Typography;

interface IProduct {
id: number;
name: string;
description: string;
price: string;
}

const ProductList: React.FC = () => {
const { listProps } = useSimpleList<IProduct>({
sorters: {
initial: [
{
field: "name",
order: "desc",
},
],
},
});

return <List {...listProps} renderItem={renderItem} />;
};

const renderItem = (item: IProduct) => {
const { id, name, description, price } = item;

return (
<List.Item actions={[<Text key={id}>{price}</Text>]}>
<List.Item.Meta title={name} description={description} />
</List.Item>
);
};

Filtering

The useSimpleList hook supports the filtering feature. You can pass the filters property to the hook to set the initial and permanent filtering state and you change the filtering state by using the setFilter function.

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

localhost:3000/products
import { useSimpleList } from "@refinedev/antd";
import { Typography, List, Input } from "antd";

const { Text } = Typography;

interface IProduct {
id: number;
name: string;
description: string;
price: string;
}

const ProductList: React.FC = () => {
const { listProps, setFilters } = useSimpleList<IProduct>({
filters: {
initial: [
{
field: "name",
operator: "contains",
value: "Awesome",
},
],
},
});

return (
<div>
<Input.Search
placeholder="Search by name"
onChange={(e) => {
setFilters([
{
field: "name",
operator: "contains",
value: e.target.value,
},
]);
}}
/>
<List {...listProps} renderItem={renderItem} />
</div>
);
};

const renderItem = (item: IProduct) => {
const { id, name, description, price } = item;

return (
<List.Item actions={[<Text key={id}>{price}</Text>]}>
<List.Item.Meta title={name} description={description} />
</List.Item>
);
};

We can use the onSearch property and the searchFormProps return value to make a custom filter form. onSearch is a function that is called when the form is submitted. searchFormProps is a property that is passed to the <Form> component.

localhost:3000/products
import { useSimpleList } from "@refinedev/antd";
import { Typography, List, Form, Input, Button } from "antd";
import { HttpError } from "@refinedev/core";

const { Text } = Typography;

interface IProduct {
id: number;
name: string;
description: string;
price: string;
}

interface ISearch {
name: string;
description: string;
}

const ProductList: React.FC = () => {
const { listProps, searchFormProps } = useSimpleList<
IProduct,
HttpError,
ISearch
>({
onSearch: (values) => {
return [
{
field: "name",
operator: "contains",
value: values.name,
},
{
field: "description",
operator: "contains",
value: values.description,
},
];
},
});

return (
<div>
<Form {...searchFormProps} layout="inline">
<Form.Item name="name">
<Input placeholder="Search by name" />
</Form.Item>
<Form.Item name="description">
<Input placeholder="Search by description" />
</Form.Item>
<Button type="primary" onClick={searchFormProps.form?.submit}>
Search
</Button>
</Form>
<List {...listProps} renderItem={renderItem} />
</div>
);
};

const renderItem = (item: IProduct) => {
const { id, name, description, price } = item;

return (
<List.Item actions={[<Text key={id}>{price}</Text>]}>
<List.Item.Meta title={name} description={description} />
</List.Item>
);
};

Realtime Updates

LiveProvider is required for this prop to work.

When the useSimpleList 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.

Properties

resource

The useSimpleList passes the resource to the dataProvider as a param. This parameter is usually used as an API endpoint path. It all depends on how to handle the resources in your dataProvider.

Refer to the creating a data provider documentation for an example of how resources are handled.

The resource value is inferred from the current route where the component or the hook is used. It can be overridden by passing the resource prop.

The use case for overriding the resource prop:

  • We can list a category from the <ProductList> page.
import React from "react";
import { HttpError } from "@refinedev/core";
import { useSimpleList } from "@refinedev/antd";

interface IProduct {
id: number;
name: string;
description: string;
price: string;
}

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

export const ProductList: React.FC = () => {
const { query: productsQuery } = useSimpleList<IProduct, HttpError>();

const { query: categoriesQuery } = useSimpleList<ICategory, HttpError>({
resource: "categories",
});

return <div>{/* ... */}</div>;
};

Also, you can give a URL path to the resource prop.

useSimpleList({
resource: "categories/subcategory", // <BASE_URL_FROM_DATA_PROVIDER>/categories/subcategory
});

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

pagination.current

Sets the initial value of the page index. It is 1 by default.

useSimpleList({
pagination: {
current: 2,
},
});

pagination.pageSize

Sets the initial value of the page size. It is 10 by default.

useSimpleList({
pagination: {
pageSize: 20,
},
});

pagination.mode

It can be "off", "server" or "client". It is "server" by default.

  • "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.
useSimpleList({
pagination: {
mode: "client",
},
});

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.

For more information, refer to the CrudSorting interface documentation

useSimpleList({
sorters: {
initial: [
{
field: "name",
order: "asc",
},
],
},
});

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.

For more information, refer to the CrudSorting interface documentation

useSimpleList({
sorters: {
permanent: [
{
field: "name",
order: "asc",
},
],
},
});

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.

For more information, refer to the CrudFilters

useSimpleList({
filters: {
initial: [
{
field: "name",
operator: "contains",
value: "Foo",
},
],
},
});

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.

For more information, refer to the CrudFilters

useSimpleList({
filters: {
permanent: [
{
field: "name",
operator: "contains",
value: "Foo",
},
],
},
});

filters.defaultBehavior

The filtering behavior can be set to either "merge" or "replace". It is merge by default.

  • 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.

useSimpleList({
filters: {
defaultBehavior: "replace",
},
});

syncWithLocation
Globally Configurable
This value can be configured globally. Click to see the guide for more information.

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

useSimpleList({
syncWithLocation: true,
});

queryOptions

useSimpleList uses the useTable hook to fetch data. You can pass the queryOptions to it like this:

useSimpleList({
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).

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

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.

useSimpleList({
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,
};
},
//...
};

dataProviderName

If there is more than one dataProvider, you can specify which one to use by passing the dataProviderName prop. This is useful when you have a different data provider for different resources.

useSimpleList({
dataProviderName: "second-data-provider",
});

successNotification

NotificationProvider is required for this prop to work.

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

useSimpleList({
successNotification: (data, values, resource) => {
return {
message: `${data.title} Successfully fetched.`,
description: "Success with no errors",
type: "success",
};
},
});

errorNotification

NotificationProvider is required for this prop to work.

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

useSimpleList({
errorNotification: (data, values, resource) => {
return {
message: `Something went wrong when getting ${data.id}`,
description: "Error",
type: "error",
};
},
});

liveMode

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.

For more information, refer to the Live / Realtime documentation

useSimpleList({
liveMode: "auto",
});

onLiveEvent

LiveProvider is required for this prop to work.

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

useSimpleList({
onLiveEvent: (event) => {
console.log(event);
},
});

liveParams

LiveProvider is required for this prop to work.

Params to pass to liveProvider's subscribe method.

onSearch

When searchFormProps.onFinish is called, the onSearch function is called with the values of the form. The onSearch function should return CrudFilters | Promise<CrudFilters>. When the onSearch function is called, the current page will be set to 1.

onSearch is useful when you want to filter the data with multiple fields by using the <Form> component.

// ...

const { searchFormProps, listProps } = useSimpleList({
onSearch: (values) => {
return [
{
field: "name",
operator: "contains",
value: values.name,
},
{
field: "description",
operator: "contains",
value: values.description,
},
];
},
});

// ...

return (
<div>
<Form {...searchFormProps} layout="inline">
<Form.Item name="name">
<Input placeholder="Search by name" />
</Form.Item>
<Form.Item name="description">
<Input placeholder="Search by description" />
</Form.Item>
<Button type="primary" onClick={searchFormProps.form?.submit}>
Search
</Button>
</Form>
<AntdList {...listProps} renderItem={renderItem} />
</div>
);

initialCurrent
deprecated

Use pagination.current instead.

initialPageSize
deprecated

Use pagination.pageSize instead.

hasPagination
deprecated

Use pagination.mode instead.

initialSorter
deprecated

Use sorters.initial instead.

permanentSorter
deprecated

Use sorters.permanent instead.

initialFilter
deprecated

Use filters.initial instead.

permanentFilter
deprecated

Use filters.permanent instead.

defaultSetFilterBehavior
deprecated

Use filters.defaultBehavior instead.

overtimeOptions

If you want the loading overtime for the request, you can pass the overtimeOptions prop to the this hook. It is useful if you want to show a loading indicator when the request takes too long. interval is the time interval in milliseconds while 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.

const { overtime } = useSimpleList({
//...
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>;
}

Return Values

query

query is the returned values from useList hook.

searchFormProps

searchFormProps returns the <Form> instance of Ant Design. When searchFormProps.onFinish is called, it will trigger onSearch function. You can also use searchFormProps.form.submit to submit the form manually.

It's useful when you want to create a filter form for your <List>.

// ...

const { searchFormProps, listProps } = useSimpleList({
onSearch: (values) => {
return [
{
field: "name",
operator: "contains",
value: values.name,
},
{
field: "description",
operator: "contains",
value: values.description,
},
];
},
});

// ...

return (
<div>
<Form {...searchFormProps} layout="inline">
<Form.Item name="name">
<Input placeholder="Search by name" />
</Form.Item>
<Form.Item name="description">
<Input placeholder="Search by description" />
</Form.Item>
<Button type="primary" onClick={searchFormProps.form?.submit}>
Search
</Button>
</Form>
<AntdList {...listProps} renderItem={renderItem} />
</div>
);

listProps

listProps is an object that contains compatible props for Ant Design [<List>][antd list] component.

dataSource

dataSource contains the data to be displayed in the list. Values are fetched with the useList hook.

loading

loading indicates whether the data is being fetched or not.

pagination

pagination returns the pagination configuration values(pageSize, current, position, etc.).

sorters

sorters is the current sorters state.

setSorters

setSorters is a function to set the currentsorters state.

 (sorters: CrudSorting) => void;

filters

filters is the current filters state.

setFilters

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

setFilters is a function to set the current filters state.

current

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

setCurrent

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

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

pageSize

pageSize is the current page size state. If pagination is disabled, it will be undefined.

setPageSize

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

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

pageCount

pageCount is the total page count state. If pagination is disabled, it will be undefined.

createLinkForSyncWithLocation

(params: SyncWithLocationParams) => string;

createLinkForSyncWithLocation is a function that creates accessible links for syncWithLocation. It takes an [SyncWithLocationParams][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.

const { overtime } = useSimpleList();

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

sorter
deprecated

Use sorters instead.

setSorter
deprecated

Use setSorters instead.

queryResult
deprecated

Use query instead.

API

Properties

PropertyTypeDescriptionDefault
resource

string

Resource name for API data interactions

Resource name that it reads from route

pagination

Pagination

Configuration for pagination

initialCurrent

initialCurrent property is deprecated. Use pagination.current instead.

number

Initial page index

1

initialPageSize

initialPageSize property is deprecated. Use pagination.pageSize instead.

number

Initial number of items per page

10

sorters

{ initial?: CrudSort[]; permanent?: CrudSort[]; mode?: "off"

"server"

undefined; }

undefined

Sort configs

initialSorter

initialSorter property is deprecated. Use sorters.initial instead.

CrudSort[]

Initial sorter state

permanentSorter

permanentSorter property is deprecated. Use sorters.permanent instead.

CrudSort[]

Default and unchangeable sorter state

[]

filters

{ initial?: CrudFilter[]; permanent?: CrudFilter[]; defaultBehavior?: SetFilterBehavior

undefined; mode?: "off"

"server"

undefined; }

undefined

Filter configs

initialFilter

initialFilter property is deprecated. Use filters.initial instead.

CrudFilter[]

Initial filter state

permanentFilter

permanentFilter property is deprecated. Use filters.permanent instead.

CrudFilter[]

Default and unchangeable filter state

[]

defaultSetFilterBehavior

defaultSetFilterBehavior property is deprecated. Use filters.defaultBehavior instead.

"merge" | "replace"

Default behavior of the setFilters function

"merge"

hasPagination

hasPagination property is deprecated. Use pagination.mode instead.

boolean

Whether to use server side pagination or not.

true

syncWithLocation

boolean

Sortings, filters, page index and records shown per page are tracked by browser history

Value set in Refine. If a custom resource is given, it will be false

queryOptions

UseQueryOptions<GetListResponse<TQueryFnData>, TError, GetListResponse<TData>, QueryKey>

react-query's useQuery options

meta

MetaQuery

Metadata query for dataProvider

metaData

metaData is deprecated with refine@4, refine will pass meta instead, however, we still support metaData for backward compatibility.

MetaQuery

Metadata query for dataProvider

dataProviderName

string

If there is more than one dataProvider, you should use the dataProviderName that you will use.

successNotification

false

OpenNotificationParams

((data?: GetListResponse<TData>, values?: { config?: UseListConfig; ... 6 more ...; dataProviderName?: string

undefined; }

undefined, resource?: string

undefined) => false

OpenNotificationParams)

undefined

Success notification configuration to be displayed when the mutation is successful.

'"There was an error creating resource (status code: statusCode)" or "Error when updating resource (status code: statusCode)"'

errorNotification

false

OpenNotificationParams

((error?: TError, values?: { config?: UseListConfig; pagination?: Pagination

undefined; ... 5 more ...; dataProviderName?: string

undefined; }

undefined, resource?: string

undefined) => false

OpenNotificationParams)

undefined

Error notification configuration to be displayed when the mutation fails.

'"There was an error creating resource (status code: statusCode)" or "Error when updating resource (status code: statusCode)"'

liveMode

Whether to update data automatically ("auto") or not ("manual") if a related live event is received. The "off" value is used to avoid creating a subscription.

"off"

onLiveEvent

Callback to handle all related live events of this hook.

undefined

liveParams

Params to pass to liveProvider's subscribe method if liveMode is enabled.

undefined

overtimeOptions

UseLoadingOvertimeCoreOptions

onSearch

((data: TSearchVariables) => CrudFilters

Promise<CrudFilters>)

Type Parameters

PropertyDescriptionTypeDefault
TQueryFnDataResult data returned by the query function. Extends BaseRecordBaseRecordBaseRecord
TErrorCustom error object that extends HttpErrorHttpErrorHttpError
TSearchVariablesAntd form values{}{}
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
queryResult of the query of a recordQueryObserverResult<{ data: TData }>
searchFormPropsAnt design Form propsForm
listPropsAnt design List propsList
totalPageTotal page count (returns undefined if pagination is disabled)number | undefined
currentCurrent page index state (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 stateCrudSorting
setSortersA function that accepts a new sorters state.(sorters: CrudSorting) => void
sorterCurrent sorting stateCrudSorting
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
overtimeOvertime loading props{ elapsedTime?: number }