Skip to content

Commit 54fa3f5

Browse files
committed
fix: Select fires onChange on load
1 parent b639e32 commit 54fa3f5

File tree

1 file changed

+11
-11
lines changed

1 file changed

+11
-11
lines changed

src/components/Select.tsx

Lines changed: 11 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -106,7 +106,6 @@ export const Select = React.forwardRef(
106106
value,
107107
onChange,
108108
render = (e) => (typeof e === 'string' ? e : e.value),
109-
as,
110109
ListItemProps,
111110
...rest
112111
} = props
@@ -124,9 +123,13 @@ export const Select = React.forwardRef(
124123
const [controlledScrolling, setControlledScrolling] = useState(false)
125124
const [touch, setTouch] = useState(false)
126125

127-
useEffect(() => {
128-
if (onChange) onChange(items[selectedIndex])
129-
}, [selectedIndex])
126+
const handleCommit = (index: number): void => {
127+
setSelectedIndex(index)
128+
if (onChange) {
129+
onChange(items[index])
130+
}
131+
setOpen(false)
132+
}
130133

131134
useEffect(() => {
132135
const idx = items.findIndex((it) =>
@@ -179,7 +182,7 @@ export const Select = React.forwardRef(
179182
useTypeahead(context, {
180183
listRef: listContentRef,
181184
activeIndex,
182-
onMatch: open ? setActiveIndex : setSelectedIndex,
185+
onMatch: open ? setActiveIndex : handleCommit,
183186
}),
184187
])
185188

@@ -339,14 +342,12 @@ export const Select = React.forwardRef(
339342
onKeyDown(e) {
340343
allowSelectRef.current = true
341344
if (e.key === 'Enter' && allowSelectRef.current) {
342-
setSelectedIndex(i)
343-
setOpen(false)
345+
handleCommit(i)
344346
}
345347
},
346348
onClick() {
347349
if (allowSelectRef.current) {
348-
setSelectedIndex(i)
349-
setOpen(false)
350+
handleCommit(i)
350351
}
351352
},
352353
onMouseUp() {
@@ -355,8 +356,7 @@ export const Select = React.forwardRef(
355356
}
356357

357358
if (allowSelectRef.current) {
358-
setSelectedIndex(i)
359-
setOpen(false)
359+
handleCommit(i)
360360
}
361361

362362
clearTimeout(selectTimeoutRef.current)

0 commit comments

Comments
 (0)