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

useList

useList is an extended version of TanStack Query's useQuery. It supports all the features of useQuery and adds some extra features.

  • It uses the getList method as the query function from the dataProvider which is passed to <Refine>.

  • It uses a query key to cache the data. The query key is generated from the provided properties. You can see the query key by using the TanStack Query devtools.

When you need to fetch data according to sort, filter, pagination, etc. from a resource, you can use the useList hook. It will return the data and some functions to control the query.

Basic Usage

Here is a basic example of how to use the useList hook.

http://localhost:3000
import { useList, HttpError } from "@refinedev/core";

interface IProduct {
id: number;
name: string;
material: string;
}

const ProductList: React.FC = () => {
const { data, isLoading, isError } = useList<IProduct, HttpError>({
resource: "products",
});

const products = data?.data ?? [];

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

if (isError) {
return <div>Something went wrong!</div>;
}

return (
<ul>
{products.map((product) => (
<li key={product.id}>
<h4>
{product.name} - ({product.material})
</h4>
</li>
))}
</ul>
);
};

Pagination

The useList hook supports the pagination feature. You can pass the pagination property to enable pagination. To handle pagination, the useList hook passes the pagination property to the getList method from the dataProvider.

Dynamically changing the pagination properties will trigger a new request.

http://localhost:3000
import { useState } from "react";
import { useList, HttpError } from "@refinedev/core";

interface IProduct {
id: number;
name: string;
material: string;
}

const ProductList: React.FC = () => {
const [current, setCurrent] = useState(1);
const [pageSize, setPageSize] = useState(5);

const { data, isLoading, isError } = useList<IProduct, HttpError>({
resource: "products",
pagination: {
current,
pageSize,
},
});

const products = data?.data ?? [];

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

if (isError) {
return <div>Something went wrong!</div>;
}

return (
<div>
<button onClick={() => setCurrent((prev) => prev - 1)}>
{"<"}
</button>
<span> page: {current} </span>
<button onClick={() => setCurrent((prev) => prev + 1)}>
{">"}
</button>
<span> per page: </span>
<select
value={pageSize}
onChange={(e) => setPageSize(Number(e.target.value))}
>
{[5, 10, 20].map((size) => (
<option key={size} value={size}>
{size}
</option>
))}
</select>

<ul>
{products.map((product) => (
<li key={product.id}>
<h4>
{product.name} - ({product.material})
</h4>
</li>
))}
</ul>
</div>
);
};

Sorting

The useList hook supports the sorting feature. You can pass the sorters property to enable sorting. To handle sorting, the useList hook passes the sorters property to the getList method from the dataProvider.

Dynamically changing the sorters property will trigger a new request.

http://localhost:3000
import { useState } from "react";
import { useList, HttpError } from "@refinedev/core";

interface IProduct {
id: number;
name: string;
material: string;
}

const ProductList: React.FC = () => {
const [order, setOrder] = useState<"asc" | "desc">("asc");

const { data, isLoading, isError } = useList<IProduct, HttpError>({
resource: "products",
sorters: [
{
field: "name",
order,
},
],
});

const products = data?.data ?? [];

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

if (isError) {
return <div>Something went wrong!</div>;
}

return (
<div>
<button
onClick={() =>
setOrder((prev) => (prev === "asc" ? "desc" : "asc"))
}
>
toggle sort
</button>

<ul>
{products.map((product) => (
<li key={product.id}>
<h4>
{product.name} - ({product.material})
</h4>
</li>
))}
</ul>
</div>
);
};

Filtering

The useList hook supports the filtering feature. You can pass the filters property to enable filtering. To handle filtering, the useList hook passes the filters property to the getList method from the dataProvider.

Dynamically changing the filters property will trigger a new request.

http://localhost:3000
import { useState } from "react";
import { useList, HttpError } from "@refinedev/core";

interface IProduct {
id: number;
name: string;
material: string;
}

const ProductList: React.FC = () => {
const [value, setValue] = useState("Cotton");

const { data, isLoading, isError } = useList<IProduct, HttpError>({
resource: "products",
filters: [
{
field: "material",
operator: "eq",
value,
},
],
});

const products = data?.data ?? [];

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

if (isError) {
return <div>Something went wrong!</div>;
}

return (
<div>
<span> material: </span>
<select value={value} onChange={(e) => setValue(e.target.value)}>
{["Cotton", "Bronze", "Plastic"].map((material) => (
<option key={material} value={material}>
{material}
</option>
))}
</select>

<ul>
{products.map((product) => (
<li key={product.id}>
<h4>
{product.name} - ({product.material})
</h4>
</li>
))}
</ul>
</div>
);
};

Realtime Updates

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

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

Refer to the liveProvider documentation for more information &#8594

Properties

resource
required

It will be passed to the getList method from the dataProvider as a parameter. 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.

useList({
resource: "categories",
});

dataProviderName

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

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

filters

filters will be passed to the getList method from the dataProvider as a parameter. It is used to send filter query parameters to the API.

Refer to the CrudFilters interface for more information &#8594

useList({
filters: [
{
field: "title",
operator: "contains",
value: "Foo",
},
],
});

sorters

sorters will be passed to the getList method from the dataProvider as a parameter. It is used to send sort query parameters to the API.

Refer to the CrudSorting interface for more information &#8594

useList({
sorters: [
{
field: "title",
order: "asc",
},
],
});

pagination

pagination will be passed to the getList method from the dataProvider as a parameter. It is used to send pagination query parameters to the API.

current

You can pass the current page number to the pagination property.

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

pageSize

You can pass the pageSize to the pagination property.

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

mode

It can be "off", "client" or "server". It is used to determine whether to use server-side pagination or not.

useList({
pagination: {
mode: "off",
},
});

queryOptions

queryOptions is used to pass additional options to the useQuery hook. It is useful when you want to pass additional options to the useQuery hook.

Refer to the useQuery documentation for more information &#8594

useList({
queryOptions: {
retry: 3,
},
});

meta

meta is used following two purposes:

  • To pass additional information to data provider methods.
  • Generate GraphQL queries using plain JavaScript Objects (JSON). Please refer GraphQL 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.

useList({
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 } = await httpClient.get(`${url}`, { headers });

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

successNotification

NotificationProvider is required for this prop to work.

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

useList({
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, useList will call open function from NotificationProvider to show an error notification. With this prop, you can customize the error notification.

useList({
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 about live mode, please check Live / Realtime page.

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

onLiveEvent

LiveProvider is required for this prop to work.

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

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

liveParams

LiveProvider is required for this prop to work.

Params to pass to liveProvider's subscribe method.

config

Deprecated

Use pagination, sorters, and filters instead.

hasPagination

Deprecated

Use pagination.mode instead.

hasPagination will be passed to the getList method from the dataProvider as a parameter. It is used to determine whether to use server-side pagination or not.

useList({
hasPagination: false,
});

Return Values

Returns an object with TanStack Query's useQuery return values.

Refer to the useQuery documentation for more information &#8594

API

Properties

Type Parameters

PropertyDesriptionTypeDefault
TQueryFnDataResult data returned by the query function. Extends BaseRecordBaseRecordBaseRecord
TErrorCustom error object that extends HttpErrorHttpErrorHttpError
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

DescriptionType
Result of the TanStack Query's useQueryQueryObserverResult<{
data: TData[];
total: number; },
TError>