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

useInfiniteList

The useInfiniteList hook is an extended version of TanStack Query's useInfiniteQuery used for retrieving items from a resource with pagination, sort, and filter configurations. It is ideal for lists where the total number of records is unknown and the user loads the next pages with a button.

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

Usage

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

localhost:3000/categories
import React from "react";
import { useInfiniteList } from "@refinedev/core";

const PostList = () => {
const {
data,
isError,
isLoading,
hasNextPage,
fetchNextPage,
isFetchingNextPage,
} = useInfiniteList({
resource: "categories",
pagination: {
pageSize: 4,
},
});

if (isLoading) {
return <p>Loading</p>;
}
if (isError) {
return <p>Something went wrong</p>;
}

const allPages = [].concat(...(data?.pages ?? []).map((page) => page.data));

return (
<div>
<ul>
{allPages.map(({ id, title }) => (
<li key={id}>
{id}.{title}
</li>
))}
</ul>
{hasNextPage && (
<button onClick={() => fetchNextPage()} disabled={isFetchingNextPage}>
{isFetchingNextPage ? "Loading more..." : "Load More"}
</button>
)}
</div>
);
};

Pagination

The useInfiniteList hook supports pagination properties just like useList. To handle pagination, the useInfiniteList hook passes the pagination property to the getList method from the dataProvider.

Dynamically changing the pagination properties will trigger a new request. The fetchNextPage method will increase the pagination.current property by one and trigger a new request as well.

Retrieving the Total Row Count

When the getList method is called via useInfiniteList, it should ideally return the total count of rows (rowCount). The way this count is obtained depends on the data provider in use:

  • REST Providers: Commonly obtain the total count from the x-total-count header.
  • GraphQL Providers: Often source the count from specific data fields like pageInfo.total.
  • Other Providers: Follow their own practices for obtaining the total count.

If the data provider doesn't return a specific count, the getList method may fall back to using the length of the paginated data array as the rowCount.

For more information on how this works, refer to the getList method documentation.

import { useInfiniteList } from "@refinedev/core";

const postListQueryResult = useInfiniteList({
resource: "posts",
pagination: { current: 3, pageSize: 8 },
});

Sorting

The useInfiniteList hook supports the sorting feature, which you can enable by passing the sorters property. useInfiniteList will then pass this property to the getList method from the dataProvider.

Dynamically changing the sorters property will trigger a new request.

localhost:3000/products
import { useState } from "react";
import { useInfiniteList, 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,
hasNextPage,
fetchNextPage,
isFetchingNextPage,
} = useInfiniteList<IProduct, HttpError>({
resource: "products",
sorters: [
{
field: "name",
order,
},
],
});

if (isLoading) {
return <p>Loading</p>;
}
if (isError) {
return <p>Something went wrong</p>;
}

const allPages = [].concat(...(data?.pages ?? []).map((page) => page.data));

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

<ul>
{allPages.map((product) => (
<li key={product.id}>
{product.name} - ({product.material})
</li>
))}
</ul>

{hasNextPage && (
<button onClick={() => fetchNextPage()} disabled={isFetchingNextPage}>
{isFetchingNextPage ? "Loading more..." : "Load More"}
</button>
)}
</div>
);
};

Filtering

The useInfiniteList hook supports the filtering feature, which you can enable by passing the filters property. useInfiniteList will then pass this property to the getList method from the dataProvider.

Dynamically changing the filters property will trigger a new request.

localhost:3000/products
import { useState } from "react";
import { useInfiniteList, 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,
hasNextPage,
fetchNextPage,
isFetchingNextPage,
} = useInfiniteList<IProduct, HttpError>({
resource: "products",
filters: [
{
field: "material",
operator: "eq",
value,
},
],
});

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

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

const allPages = [].concat(...(data?.pages ?? []).map((page) => page.data));

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>
{allPages.map((product) => (
<li key={product.id}>
{product.name} - ({product.material})
</li>
))}
</ul>

{hasNextPage && (
<button onClick={() => fetchNextPage()} disabled={isFetchingNextPage}>
{isFetchingNextPage ? "Loading more..." : "Load More"}
</button>
)}
</div>
);
};

Realtime Updates

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

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

Properties

resource
required

This parameter will be passed to the getList method from the dataProvider as a parameter. It is usually used as an API endpoint path but it all depends on how you handle the resource in the getList method.

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

For more information, refer to the creating a data provider tutorial

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

This prop allows you to specify which dataProvider if you have more than one. Just pass it like in the example:

useInfiniteList({
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.

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

For more information, refer to the CrudFilters interface

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.

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

For more information, refer to the CrudSorting interface

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.

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

pageSize

You can pass the pageSize to the pagination property.

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

mode

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

useInfiniteList({
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.

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

For more information, refer to the useQuery documentation

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.

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

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

successNotification

NotificationProvider is required for this prop to work.

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

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

useInfiniteList({
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.

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

onLiveEvent

LiveProvider is required for this prop to work.

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

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

liveParams

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.

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

config
deprecated

Use pagination, hasPagination, sorters and filters instead.

hasPagination
deprecated

Use pagination.mode instead.

Return Values

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

For more information, refer to the useInfiniteQuery documentation

Additional Values

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 } = useInfiniteList();

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

FAQ

How to use cursor-based pagination?

Some APIs use the cursor-pagination method for its benefits. This method uses a cursor object to determine the next set of data. The cursor can be a number or a string and is passed to the API as a query parameter.

Preparing the data provider:

Consumes data from data provider useInfiniteList with the getList method. First of all, we need to make this method in the data provider convenient for this API. The cursor data is kept in pagination and should be set to 0 by default.

getList: async ({ resource, pagination }) => {
const { current } = pagination;
const { data } = await axios.get(
`https://api.fake-rest.refine.dev/${resource}?cursor=${current || 0}`,
);

return {
data: data[resource],
total: 0,
};
},
TIP

As the total data is only needed in the offset-pagination method, define it as 0 here.

After this process, we successfully retrieved the first page of data. Let's fill the cursor object for the next page.

getList: async ({ resource, pagination }) => {
const { current } = pagination;
const { data } = await axios.get(
`https://api.fake-rest.refine.dev/${resource}?cursor=${current || 0}`,
);

return {
data: data[resource],
total: 0,
cursor: {
next: data.cursor.next,
prev: data.cursor.prev,
},
};
},

How to override the getNextPageParam method?

By default, Refine expects you to return the cursor object, but is not required. This is because some APIs don't work that way. To fix this problem you need to override the getNextPageParam method and return the next cursor.

import { useInfiniteList } from "@refinedev/core";

const {
data,
error,
hasNextPage,
isLoading,
fetchNextPage,
isFetchingNextPage,
} = useInfiniteList({
resource: "posts",
queryOptions: {
// When you override this method, you can access the `lastPage` and `allPages`.
getNextPageParam: (lastPage, allPages) => {
// return the last post's id
const { data } = lastPage;
const lastPost = data[data.length - 1];
return lastPost.id;
},
},
});

API Reference

Properties

PropertyTypeDescriptionDefault
resource

string

Resource name for API data interactions

queryOptions

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

Tanstack Query's useInfiniteQuery 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

config

config property is deprecated. Use pagination, hasPagination, sorters and filters instead.

Configuration for pagination, sorting and filtering

pagination

Pagination

Pagination properties

hasPagination

hasPagination property is deprecated. Use pagination.mode instead.

boolean

Whether to use server-side pagination or not

sorters

CrudSort[]

Sorter parameters

filters

CrudFilter[]

Filter parameters

dataProviderName

string

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

successNotification

false

OpenNotificationParams

((data?: InfiniteData<GetListResponse<TData>>, values?: { meta?: MetaQuery; ... 6 more ...; dataProviderName?: string

undefined; }

undefined, resource?: string

undefined) => false

... 1 more ...

undefined)

undefined

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

false

errorNotification

false

OpenNotificationParams

((error?: TError, values?: { meta?: MetaQuery; metaData?: MetaQuery

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

undefined; }

undefined, resource?: string

undefined) => false

... 1 more ...

undefined)

undefined

Error notification configuration to be displayed when the mutation fails.

"Error (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

Type Parameters

PropertyDescriptionTypeDefault
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 useInfiniteQueryInfiniteQueryObserverResult<{ data: TData[]; total: number; }, TError>
overtime{ elapsedTime?: number }

Example

Run on your local
npm create refine-app@latest -- --example use-infinite-list