Skip to main content
Version: 3.xx.xx

useAutocomplete

The useAutocomplete hook is used to get data from the API and to manage the Material UI <Autocomplete> component.

Usage with React Hook Form (@pankod/refine-react-hook-form)​

We'll demonstrate how to get data at /categories endpoint from https://api.fake-rest.refine.dev REST API.

https://api.fake-rest.refine.dev/categories
{
[
{
id: 1,
title: "E-business",
},
{
id: 2,
title: "Virtual Invoice Avon",
},
{
id: 3,
title: "Unbranded",
},
]
}
pages/posts/create.tsx
import { HttpError } from "@pankod/refine-core";
import {
Create,
Box,
Autocomplete,
useAutocomplete,
TextField,
} from "@pankod/refine-mui";
import { useForm, Controller } from "@pankod/refine-react-hook-form";

export const PostCreate = () => {
const {
saveButtonProps,
refineCore: { formLoading, queryResult },
register,
control,
formState: { errors },
} = useForm<IPost, HttpError, IPost & { category: ICategory }>();

const { autocompleteProps } = useAutocomplete<ICategory>({
resource: "categories",
});

return (
<Create isLoading={formLoading} saveButtonProps={saveButtonProps}>
<Box component="form">
<Controller
control={control}
name="category"
rules={{ required: "This field is required" }}
render={({ field }) => (
<Autocomplete
{...autocompleteProps}
{...field}
onChange={(_, value) => {
field.onChange(value);
}}
getOptionLabel={(item) => {
return (
autocompleteProps?.options?.find(
(p) =>
p?.id?.toString() ===
item?.id?.toString(),
)?.title ?? ""
);
}}
isOptionEqualToValue={(option, value) =>
value === undefined ||
option.id.toString() === value.toString()
}
renderInput={(params) => (
<TextField
{...params}
label="Category"
margin="normal"
variant="outlined"
error={!!errors.category}
helperText={errors.category?.message}
required
/>
)}
/>
)}
/>
</Box>
</Create>
);
};

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

export interface IPost {
id: number;
category: { id: number };
}

The use of useAutocomplete with useForm is demonstrated in the code above. You can use the useAutocomplete hook independently of the useFormhook.

Basic use of Autocomplete

Search functionality

info

By default, refine does the search using the useList hook and passes it to the search parameter. If you get a problem you should check your getList function in your Data Provider. If you want to change this behavior to make client-side filtering, you can examine this documentation.

Options​

resource​

const { autocompleteProps } = useAutocomplete({
resource: "categories",
});

resource property determines API resource endpoint to fetch records from dataProvider. It returns properly configured options values for <Autocomplete> options.

Refer to Material UI Autocomplete component documentation for detailed info for options. β†’

defaultValue​

const { autocompleteProps } = useAutocomplete({
resource: "categories",
defaultValue: "1",
});

Adds extra options to <Autocomplete> component. It uses useMany so defaultValue can be an array of strings like follows.

defaultValue: ["1", "2"],

Refer to the useMany documentation for detailed usage. β†’

tip

Can use defaultValue property when edit a record in <Edit> component.

filters​

const { autocompleteProps } = useAutocomplete({
resource: "categories",
filters: [
{
field: "isActive",
operator: "eq",
value: true,
},
],
});

It allows us to add some filters while fetching the data. For example, if you want to list only the active records.

sort​

const { autocompleteProps } = useAutocomplete({
resource: "categories",
sort: [
{
field: "title",
order: "asc",
},
],
});

It allows us to sort the options. For example, if you want to sort your list according to title by ascending.

fetchSize​

const { autocompleteProps } = useAutocomplete({
resource: "categories",
fetchSize: 20,
});

Amount of records to fetch in the select box.

onSearch​

const { autocompleteProps } = useAutocomplete({
resource: "categories",
onSearch: (value) => [
{
field: "title",
operator: "containss",
value,
},
],
});

If defined, it allows us to override the filters to use when fetching the list of records. Thus, it. It should return CrudFilters.

queryOptions​

const { autocompleteProps } = useAutocomplete({
resource: "categories",
queryOptions: {
onError: () => {
console.log("triggers when on query return Error");
},
},
});

useQuery options can be set by passing queryOptions property.

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 { autocompleteProps } = useAutocomplete({
resource: "categories",
defaultValueQueryOptions: {
onSuccess: (data) => {
console.log("triggers when on query return on success");
},
},
});

useQuery options for default value query can be set by passing queryOptions property.

API Reference​

Properties​

PropertyDescriptionTypeDefault
resource
Required
Resource name for API data interactionsstring
defaultValueAdds extra optionsstring | Array<string>
filtersAdd filters while fetching the dataCrudFilters
sortAllow us to sort the optionsCrudSorting
debounceThe number of milliseconds to delaynumber300
queryOptionsreact-query useQuery options UseQueryOptions<GetListResponse<TData>, TError>
defaultValueQueryOptionsreact-query useQuery options UseQueryOptions<GetManyResponse<TData>, TError>
fetchSizeAmount of records to fetch in select box list.numberundefined
onSearchIf defined, this callback allows us to override all filters for every search request.(value: string) => CrudFilters | Promise<CrudFilters>undefined
metaDataMetadata query for dataProviderMetaDataQuery{}
liveModeWhether 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."auto" | "manual" | "off""off"
liveParamsParams to pass to liveProvider's subscribe method if liveMode is enabled.{ ids?: string[]; [key: string]: any; }undefined
onLiveEventCallback to handle all related live events of this hook.(event: LiveEvent) => voidundefined

Return values​

PropertyDescriptionType
autocompletePropsMaterial UI Autocomplete propsAutoCompleteReturnValues
queryResultResult of the query of a recordQueryObserverResult<{ data: TData }>
defaultValueQueryResultResult of the query of a defaultValue recordQueryObserverResult<{ data: TData }>

AutoCompleteReturnValues​

PropertyDescriptionType
optionsArray of optionsTData
loadingLoading stateboolean
onInputChangeCallback fired when the input value changes(event: React.SyntheticEvent, value: string, reason: string) => void
filterOptionsDetermines the filtered options to be rendered on search.(options: TData, state: object) => TData

Live StackBlitz Example​