Skip to content

Commit

Permalink
Merge pull request #129 from osstotalsoft/bugfix/autocomplete-lazy-lo…
Browse files Browse the repository at this point in the history
…ading

Bugfix/autocomplete lazy loading
  • Loading branch information
alexandra-c authored Sep 5, 2024
2 parents f1909fc + 8bcef33 commit 5eb6816
Showing 1 changed file with 9 additions and 14 deletions.
23 changes: 9 additions & 14 deletions src/components/inputs/Autocomplete/Autocomplete.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -111,30 +111,30 @@ const Autocomplete: React.FC<AutocompleteProps<any, any, any, any>> = ({
)

const handleLoadOptions = useCallback(
(input?: string) => {
async (input?: string) => {
if (!loadOptions) return
if (!isPaginated) {
setLocalLoading(true)
;(loadOptions as LoadOptions)(input).then(loadedOptions => {
setAsyncOptions(loadedOptions || [])
setLocalLoading(false)
})
const loadedOptions = await (loadOptions as LoadOptions)(input)
setAsyncOptions(loadedOptions || [])
setLocalLoading(false)
} else handleLoadOptionsPaginated(input)
},
[handleLoadOptionsPaginated, isPaginated, loadOptions]
)

const handleMenuOpen = useCallback(
(event: React.SyntheticEvent<Element, Event>) => {
async (event: React.SyntheticEvent<Element, Event>) => {
if (onOpen) onOpen(event)
handleLoadOptions(localInput)
await handleLoadOptions(localInput)
},
[handleLoadOptions, localInput, onOpen]
)

const handleMenuClose = useCallback(
(event: React.SyntheticEvent<Element, Event>, reason: AutocompleteCloseReason) => {
setLocalInput('')
setAsyncOptions([])
if (onClose) onClose(event, reason)
},
[onClose]
Expand Down Expand Up @@ -269,21 +269,16 @@ const Autocomplete: React.FC<AutocompleteProps<any, any, any, any>> = ({
)

const handleInputChange = useCallback(
(event: React.SyntheticEvent, value: string, reason: AutocompleteInputChangeReason) => {
async (event: React.SyntheticEvent, value: string, reason: AutocompleteInputChangeReason) => {
setLocalInput(value ? value : '')
if (onInputChange) onInputChange(event, value, reason)

// this prevents the component from calling loadOptions again when the user clicks outside it and the menu closes
if (event?.nativeEvent?.type === 'focusout') {
return
}

if (loadOptions) {
setLocalLoading(true)
handleLoadOptions(value)
}
},
[handleLoadOptions, loadOptions, onInputChange]
[onInputChange]
)

useEffect(() => {
Expand Down

0 comments on commit 5eb6816

Please sign in to comment.