Skip to content

Commit 38aa677

Browse files
committed
fix: utilize debounced value for selecting the option no
1 parent e708e38 commit 38aa677

File tree

1 file changed

+15
-15
lines changed

1 file changed

+15
-15
lines changed

src/components/ui/combobox.tsx

Lines changed: 15 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ import {
1313
PopoverContent,
1414
PopoverTrigger,
1515
} from "@/components/ui/popover";
16+
import { useDebounce } from "@/hooks/use-debounce";
1617
import { cn } from "@/lib/utils";
1718
import type React from "react";
1819
import { useEffect, useRef, useState } from "react";
@@ -42,13 +43,25 @@ export const LinearCombobox = ({
4243
const [searchValue, setSearchValue] = useState("");
4344
const onValueChangeRef = useRef(onValueChange);
4445
const isSearching = searchValue.length > 0;
45-
46+
const { debouncedValue } = useDebounce(searchValue);
4647
useEffect(() => {
4748
if (selectedOption && onValueChangeRef.current) {
4849
onValueChangeRef.current(selectedOption);
4950
}
5051
}, [selectedOption]);
5152

53+
useEffect(() => {
54+
if (Number.parseInt(debouncedValue) < options.length) {
55+
const possibleOption = options[Number.parseInt(debouncedValue)];
56+
if (possibleOption) {
57+
setSelectedOption(possibleOption);
58+
setOpenPopover(false);
59+
setSearchValue("");
60+
return;
61+
}
62+
}
63+
}, [debouncedValue, options]);
64+
5265
return (
5366
<Popover open={openPopover} onOpenChange={setOpenPopover} modal>
5467
<PopoverTrigger asChild>
@@ -85,19 +98,7 @@ export const LinearCombobox = ({
8598
<Command className="rounded-lg relative">
8699
<CommandInput
87100
value={searchValue}
88-
onValueChange={(searchValue) => {
89-
// If the user types a number, then set as the selected option
90-
if (Number.parseInt(searchValue) < options.length) {
91-
const possibleOption = options[Number.parseInt(searchValue)];
92-
if (possibleOption) {
93-
setSelectedOption(possibleOption);
94-
setOpenPopover(false);
95-
setSearchValue("");
96-
return;
97-
}
98-
}
99-
setSearchValue(searchValue);
100-
}}
101+
onValueChange={setSearchValue}
101102
className="text-[0.8125rem] leading-normal"
102103
placeholder="Type Option no"
103104
/>
@@ -131,7 +132,6 @@ export const LinearCombobox = ({
131132
</div>
132133
</CommandItem>
133134
))}
134-
135135
{children && (
136136
<>
137137
<CommandSeparator />

0 commit comments

Comments
 (0)