Skip to content

Commit 5b4aa0e

Browse files
committed
feat: allow passing value prop to trigger a search
1 parent 6bddec3 commit 5b4aa0e

File tree

1 file changed

+21
-8
lines changed

1 file changed

+21
-8
lines changed

src/autocomplete/autocomplete.js

Lines changed: 21 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ export default ({
1616
params,
1717
options,
1818
placeholder = strings.inputPlaceholder,
19+
value = '',
1920
autoFocus = false,
2021
debounce: debounceWait = 200,
2122
onSelect: userOnSelectItem,
@@ -37,15 +38,14 @@ export default ({
3738

3839
// search queries the autocomplete API
3940
const search = useCallback(text => {
40-
if (!text) return
41-
4241
autocomplete(text).then(({ features, discard }) => {
4342
if (discard || inputRef.current.value !== text) {
4443
return
4544
}
4645

4746
setIsLoading(false)
4847
setResults({ text, features })
48+
openMenu()
4949
})
5050
.catch(onError)
5151
}, [autocomplete])
@@ -57,20 +57,27 @@ export default ({
5757

5858
const onInputValueChange = ({ type, inputValue }) => {
5959
const term = inputValue.trim()
60-
if (term === '') {
61-
setIsLoading(false)
62-
setResults(emptyResults)
63-
}
6460

6561
// call user-supplied onChange callback
6662
if (typeof userOnChange === 'function') {
6763
userOnChange(term)
6864
}
6965

66+
if (term === '') {
67+
setIsLoading(false)
68+
setResults(emptyResults)
69+
return
70+
}
71+
7072
// only search if the input value actually changed and not if an item was selected,
7173
// which also fires this callback. this prevents an additional request after the user has already
7274
// selected an item.
73-
if (type === useCombobox.stateChangeTypes.InputChange && term.length > 0) {
75+
const searchOn = [
76+
useCombobox.stateChangeTypes.InputChange,
77+
useCombobox.stateChangeTypes.FunctionSetInputValue
78+
]
79+
80+
if (searchOn.includes(type)) {
7481
setIsLoading(true)
7582
debouncedSearch(term)
7683
}
@@ -101,6 +108,10 @@ export default ({
101108
}
102109
}, [autoFocus])
103110

111+
// if an initial value is provided trigger a search with that, which allows
112+
// programmatically setting the value attribute, for example for a typewriter effect
113+
useEffect(() => setInputValue(value), [value])
114+
104115
// downshift combobox
105116
const {
106117
isOpen,
@@ -109,7 +120,9 @@ export default ({
109120
getInputProps,
110121
getComboboxProps,
111122
highlightedIndex,
112-
getItemProps
123+
getItemProps,
124+
setInputValue,
125+
openMenu
113126
} = useCombobox({
114127
environment,
115128
itemToString,

0 commit comments

Comments
 (0)