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

useSelect

useSelect hook allows you to manage any select (like a Html <select> tag, React Select, etc...) component. Since it is designed as headless, It expects you to handle the UI.

This hook uses the useList hook for fetching data.

Derivatives and Extended Versions:

If you're looking for a complete select library, Refine has out-of-the-box support for the libraries below:

For more information, refer to the useList hook→

Usage

Here is a basic example of how to use useSelect hook.

localhost:3000/products
import { useSelect } from "@refinedev/core";

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

const ProductCreate: React.FC = () => {
const { options } = useSelect<ICategory>({
resource: "categories",
});

return (
<label>
Select a category:
<select>
{options?.map((option) => (
<option key={option.value} value={option.value}>
{option.label}
</option>
))}
</select>
</label>
);
};

Realtime Updates

LiveProvider is required for this prop to work.

When useSelect 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 the live updates.

Properties

resource
required

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.

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

For more information, refer to the creating a data provider

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

optionLabel and optionValue

Allows you to change the value and label of your options. Default values are optionLabel = "title" and optionValue = "id"

useSelect<ICategory>({
resource: "products",
optionLabel: "name"
optionValue: "productId"
});

These properties also supports nested property access with Object path syntax.

const { options } = useSelect({
resource: "categories",
optionLabel: "nested.title",
optionValue: "nested.id",
});

It's also possible to pass function to these props. These functions will receive item argument.

const { options } = useSelect({
optionLabel: (item) => `${item.firstName} ${item.lastName}`,
optionValue: (item) => item.id,
});

searchField

Can be used to specify which field will be searched with value given to onSearch function.

const { onSearch } = useSelect({ searchField: "name" });

onSearch("John"); // Searches by `name` field with value John.

By default, it uses optionLabel's value, if optionLabel is a string. Uses title field otherwise.

// When `optionLabel` is string.
const { onSearch } = useSelect({ optionLabel: "name" });

onSearch("John"); // Searches by `name` field with value John.

// When `optionLabel` is function.
const { onSearch } = useSelect({
optionLabel: (item) => `${item.id} - ${item.name}`,
});

onSearch("John"); // Searches by `title` field with value John.

sorters

It allows to show the options in the desired order. sorters will be passed to the getList method from the dataProvider as parameter via the useList hook. It is used to send sort query parameters to the API.

useSelect({
sorters: [
{
field: "title",
order: "asc",
},
],
});
localhost:3000/products
import { useSelect } from "@refinedev/core";

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

const ProductCreate: React.FC = () => {
const [order, setOrder] = React.useState<"asc" | "desc">("asc");
const { options } = useSelect<ICategory>({
resource: "categories",
sorters: [
{
field: "title",
order,
},
],
});

return (
<>
<label>
Select a category:
<select>
{options?.map((option) => (
<option key={option.value} value={option.value}>
{option.label}
</option>
))}
</select>
<button onClick={() => setOrder(order === "asc" ? "desc" : "asc")}>
Toggle
</button>
</label>
</>
);
};

For more information, refer to the CrudSorting interface

filters

It is used to show options by filtering them. filters will be passed to the getList method from the dataProvider as parameter via the useList hook. It is used to send filter query parameters to the API.

useSelect({
filter: [
{
field: "isActive",
operator: "eq",
value: true,
},
],
});

For more information, refer to the CrudFilters interface

defaultValue

Allows to make options selected by default. Adds extra options to <select> component. In some cases like there are many entries for the <select> and pagination is required, defaultValue may not be present in the current visible options and this can break the <select> component. To avoid such cases, A separate useMany query is sent to the backend with the defaultValue and appended to the options of <select>, ensuring the default values exist in the current options array. Since it uses useMany to query the necessary data, the defaultValue can be a single value or an array of values like the following:

useSelect({
defaultValue: 1, // or [1, 2]
});

selectedOptionsOrder

selectedOptionsOrder allows us to sort selectedOptions on defaultValue. It can be:

  • "in-place": sort selectedOptions at the bottom. It is by default.
  • "selected-first": sort selectedOptions at the top.
useSelect({
defaultValue: 1, // or [1, 2]
selectedOptionsOrder: "selected-first", // in-place | selected-first
});

For more information, refer to the useMany documentation

debounce

It allows us to debounce the onSearch function.

useSelect({
resource: "categories",
debounce: 500,
});

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.

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

For more information, refer to the useQuery documentation

pagination

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

current

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

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

pageSize

You can pass the pageSize to the pagination property.

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

mode

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

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

defaultValueQueryOptions

When the defaultValue property is given, the useMany data hook is called for the selected records. With this property, you can change the options of this query. If not given, the values given in queryOptions will be used.

const { options } = useSelect({
resource: "categories",
defaultValueQueryOptions: {
onSuccess: (data) => {
console.log("triggers when on query return on success");
},
},
});

onSearch

It allows us to AutoComplete the options.

localhost:3000/products
import { useSelect } from "@refinedev/core";

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

const ProductCreate: React.FC = () => {
const { options, onSearch } = useSelect<ICategory>({
resource: "categories",
onSearch: (value) => [
{
field: "title",
operator: "contains",
value,
},
],
});

return (
<>
<p>
Filter:
<input onChange={(e) => onSearch(e.target.value)} />
</p>

<select>
{options?.map((option) => (
<option key={option.value} value={option.value}>
{option.label}
</option>
))}
</select>
</>
);
};
Implementation Tips:
  • The HTML select tag does not natively support AutoComplete. If AutoComplete is desired, it can be used with React Select or use-select.
  • If onSearch is used, it will override the existing filters.
  • For more information, refer to the CrudFilters interface

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.

useSelect({
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

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.

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

successNotification

NotificationProvider is required for this prop to work.

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

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

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

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

onLiveEvent

LiveProvider is required for this prop to work.

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

useSelect({
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 } = useSelect({
//...
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>;
}

sort
deprecated

Use sorters instead.

hasPagination
deprecated

Use pagination.mode instead.

FAQ

How to get all the data without pagination?

You may want to get all the data without pagination. In this case you should use the hasPagination prop. The data provider must have the appropriate implementation in order to use this feature.

How to add search to options (Autocomplete)?

onSearch is a function that is used to set the search value. It is useful when you want to search for a specific value. A simple example of this is shown below.

localhost:3000/products
import { useSelect } from "@refinedev/core";

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

const ProductCreate: React.FC = () => {
const { options, onSearch } = useSelect<ICategory>({
resource: "categories",
onSearch: (value) => [
{
field: "title",
operator: "contains",
value,
},
],
});

return (
<>
<p>
Filter:
<input onChange={(e) => onSearch(e.target.value)} />
</p>

<select>
{options?.map((option) => (
<option key={option.value} value={option.value}>
{option.label}
</option>
))}
</select>
</>
);
};

How to ensure defaultValue is included in the options?

In some cases we only have id, it may be necessary to show it selected in the selection box. This hook sends the request via useMany, gets the data and marks it as selected.

localhost:3000/products
import { useSelect } from "@refinedev/core";

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

const ProductCreate: React.FC = () => {
const { options } = useSelect<ICategory>({
resource: "categories",
defaultValue: 20,
});

return (
<label>
Select a category:
<select>
{options?.map((option) => (
<option key={option.value} value={option.value}>
{option.value}-{option.label}
</option>
))}
</select>
</label>
);
};

How to change the label and value properties in options?

optionLabel and optionValue are used to change the value of your options. The default values are optionsLabel="title" and optionsValue="id".

To change to name and categoryId;

useSelect({
optionLabel: "name",
optionValue: "categoryId",
});

Can I create the options manually?

Sometimes it may not be enough to create optionLabel and optionValue options. In this case we create options with query.

const { query } = useSelect({
resource: "categories",
});

const options = query.data?.data.map((item) => ({
label: item.name,
value: item.id,
}));

return (
<select>
{options?.map((option) => (
<option key={option.value} value={option.value}>
{option.label}
</option>
))}
</select>
);

API Reference

Properties

PropertyTypeDescriptionDefault
resource

string

Resource name for API data interactions

optionLabel

string

((item: TData) => string)

Set the option's label value

"title"

optionValue

string

((item: TData) => string)

Set the option's value

"id"

searchField

string

If provided optionLabel is a string, uses optionLabel's value.

"title"

sort

Use sorters instead

CrudSort[]

Allow us to sort the options

sorters

CrudSort[]

Allow us to sort the options

filters

CrudFilter[]

Resource name for API data interactions

defaultValue

Adds extra options

selectedOptionsOrder

"in-place" | "selected-first"

Allow us to sort the selection options

in-place

debounce

number

The number of milliseconds to delay

300

queryOptions

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

react-query useQuery options

pagination

{ current? : number; pageSize?: number;}

Pagination option from useList()

undefined

hasPagination

hasPagination is deprecated, use pagination.mode instead.

boolean

Disabling pagination option from useList()

false

defaultValueQueryOptions

UseQueryOptions<GetManyResponse<TQueryFnData>, TError, GetManyResponse<TQueryFnData>, QueryKey>

react-query useQuery options

onSearch

((value: string) => CrudFilter[])

If defined, this callback allows us to override all filters for every search request.

undefined

meta

MetaQuery

Additional meta data to pass to the useMany from the data provider

metaData

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

MetaQuery

Additional meta data to pass to the useMany from the data provider

dataProviderName

string

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

default

fetchSize

use pagination instead

number

Amount of records to fetch in select box list.

undefined

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

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

PropertyDescriptionType
optionsIt returns possible options{ label: string; value: string }
queryResult of the query of a recordQueryObserverResult<{ data: TData; error: TError }>
defaultValueQueryResult of the query of a defaultValue recordQueryObserverResult<{ data: TData; error: TError }>
onSearchA function to set the search valueonSearch: (value: string) => void
overtimeOvertime loading props{ elapsedTime?: number }

Example

Run on your local
npm create refine-app@latest -- --example core-use-select