useSelect
useSelect
hook allows you to manage Ant Design's <Select>
component when the records in a resource needs to be used as select options.
This hook uses the useList
hook for fetching data.
For more information, refer to the useList documentation โ
Usageโ
Here is a basic example that uses the useSelect
hook.
Realtime Updatesโ
LiveProvider
is required for this prop to work.
When the useSelect
hook is mounted, it passes some parameters (channel
, resource
etc.) to the subscribe
method from the liveProvider
that allow you to subscribe to live updates.
Propertiesโ
resource requiredโ
resource
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 but it all depends on how you handle the resource
in the getList
method.
See the creating a data provider documentation for an example of how resource are handled.
useSelect({
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
section 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 support 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โ
sorters
prop allows you to show the options in the desired order. It will be passed to the getList
method from the dataProvider
as parameter via the useList
hook and used to send sort query parameters to the API.
useSelect({
sorters: [
{
field: "title",
order: "asc",
},
],
});
For more information, refer to the
CrudSorting
interface documentation โ
filtersโ
filters
is used to filter the options you are showing. filters
will be passed to the getList
method from the dataProvider
as parameter via the useList
hook and used to send filter query parameters to the API.
useSelect({
filters: [
{
field: "isActive",
operator: "eq",
value: true,
},
],
});
For more information, refer to the
CrudFilters
interface documentation โ
defaultValueโ
Is used to fetch extra options from the API.
If there are many <select>
options and pagination is needed, the defaultValue
might not be in the visible list. This can break the <select>
component. To prevent this, a separate useMany
query fetches the defaultValue
from the backend and adds it to the options, ensuring it exists in the list. Since it uses useMany
, defaultValue
can be a single value or an array:
useSelect({
defaultValue: 1, // or [1, 2]
});
INFORMATION
defaultValue
does not set a default selection. It only ensures the default value exists in the options.
To set a default selection, pass defaultValue
to the value
prop of <Select>
or useForm
:
const form = useForm({
defaultValues: {
category: { id: 1 }, // Default selected value
},
});
const { selectProps } = useSelect({
resource: "categories",
defaultValue: [1], // Ensures the default value is included in options
});
selectedOptionsOrderโ
selectedOptionsOrder
allows us to sort selectedOptions
on defaultValue
. It can be:
"in-place"
: sortselectedOptions
at the bottom. It is by default."selected-first"
: sortselectedOptions
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โ
This prop 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โ
It can be "off"
, "client"
or "server"
. It is used to determine whether to use server-side pagination or not.
useSelect({
pagination: {
mode: "off",
},
});
defaultValueQueryOptionsโ
When the defaultValue
property is given, the useMany
data hook is called for the selected records. defaultValueQueryOptions
allows you to change the options of this query.
If defaultValue
property is not given, the values given in the queryOptions
will be used instead.
const { options } = useSelect({
resource: "categories",
defaultValueQueryOptions: {
onSuccess: (data) => {
console.log("triggers when on query return on success");
},
},
});
onSearchโ
onSearch
allows the addittion of AutoComplete
to the options
.
If onSearch
is used, it will override the existing filters
.
For more information, refer to the
CrudFilters
interface documentation โ
Client-side filteringโ
Sometimes, you may want to filter the options on the client-side. You can do this by passing the onSearch
function as undefined
and setting filterOption
to true
. You can also set optionFilterProp
to label
or value
to filter the options by label or value respectively.
const { selectProps } = useSelect({
resource: "categories",
});
<Select
{...selectProps}
onSearch={undefined}
filterOption={true}
optionFilterProp="label" // or "value"
/>;
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 different data providers 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 the open
function from NotificationProvider
to show a success notification. This prop allows you to customize the success notification message
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 the open
function from NotificationProvider
to show an error notification. This prop allows you to customize the error notification message
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.
This property 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.
useSelect({
liveMode: "auto",
});
For more information, refer to the Live / Realtime documentation โ
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 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 } = 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>;
}
FAQโ
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.
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 mark as selected.
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();
const options = query.data?.data.map((item) => ({
label: item.title,
value: item.id,
}));
return <Select options={options} />;
How do I use it with CRUD
components and useForm
?โ
API Referenceโ
Propertiesโ
Property | Type | Description | Default |
---|---|---|---|
resource ๏นก |
| Resource name for API data interactions | |
optionLabel |
| Set the option's label value |
|
optionValue |
| Set the option's value |
|
searchField |
| If provided |
|
sorters |
| Allow us to sort the options | |
filters |
| Resource name for API data interactions | |
defaultValue | Adds extra | ||
selectedOptionsOrder |
| Allow us to sort the selection options |
|
debounce |
| The number of milliseconds to delay |
|
queryOptions |
| react-query useQuery options | |
pagination |
| Pagination option from |
|
defaultValueQueryOptions |
| react-query useQuery options | |
onSearch |
| If defined, this callback allows us to override all filters for every search request. |
|
meta |
| Additional meta data to pass to the | |
dataProviderName |
| Additional meta data to pass to the |
|
successNotification |
| Success notification configuration to be displayed when the mutation is successful. | '"There was an error creating resource (status code: |
errorNotification |
| Error notification configuration to be displayed when the mutation fails. | '"There was an error creating resource (status code: |
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. |
| |
onLiveEvent | Callback to handle all related live events of this hook. |
| |
liveParams | Params to pass to liveProvider's subscribe method if liveMode is enabled. |
| |
overtimeOptions |
|
Type Parametersโ
Property | Description | Type | Default |
---|---|---|---|
TQueryFnData | Result data returned by the query function. Extends BaseRecord | BaseRecord | BaseRecord |
TError | Custom error object that extends HttpError | HttpError | HttpError |
TData | Result data returned by the select function. Extends BaseRecord . If not specified, the value of TQueryFnData will be used as the default value. | BaseRecord | TQueryFnData |
Return valuesโ
Property | Description | Type |
---|---|---|
selectProps | Ant design Select props | Select |
query | Result of the query of a record | QueryObserverResult<{ data: TData }> |
defaultValueQuery | Result of the query of a defaultValue record | QueryObserverResult<{ data: TData }> |
defaultValueQueryOnSuccess | Default value onSuccess method | () => void |
overtime | Overtime loading props | { elapsedTime?: number } |
Exampleโ
npm create refine-app@latest -- --example field-antd-use-select-basic
Infinite Loading Exampleโ
npm create refine-app@latest -- --example field-antd-use-select-infinite
- Usage
- Realtime Updates
- Properties
- resource
- optionLabel and optionValue
- searchField
- sorters
- filters
- defaultValue
- selectedOptionsOrder
- debounce
- queryOptions
- pagination
- current
- pageSize
- mode
- defaultValueQueryOptions
- onSearch
- Client-side filtering
- meta
- dataProviderName
- successNotification
- errorNotification
- liveMode
- onLiveEvent
- liveParams
- overtimeOptions
- FAQ
- How to add search to options (Autocomplete)?
- How to ensure
defaultValue
is included in the options? - How to change the
label
andvalue
properties in options? - Can I create the options manually?
- How do I use it with
CRUD
components anduseForm
? - API Reference
- Properties
- Type Parameters
- Return values
- Example
- Infinite Loading Example