|
1 | 1 | import { SxProps, Theme } from '@mui/material'; |
2 | 2 | import { debounce } from 'lodash'; |
3 | | -import React, { useEffect, useState } from 'react'; |
| 3 | +import React, { useEffect, useMemo, useState } from 'react'; |
4 | 4 | import { InputAdornment } from '../../base'; |
5 | 5 | import { SearchIcon } from '../../icons'; |
6 | 6 | import { useTheme } from '../../theme'; |
@@ -33,44 +33,56 @@ interface SearchBarProps { |
33 | 33 | */ |
34 | 34 | function StyledSearchBar({ |
35 | 35 | onChange, |
36 | | - value, |
| 36 | + value = '', |
37 | 37 | label, |
38 | 38 | sx, |
39 | 39 | placeholder, |
40 | 40 | endAdornment, |
41 | 41 | debounceTime = 300 |
42 | 42 | }: SearchBarProps): JSX.Element { |
43 | 43 | const theme = useTheme(); |
44 | | - const [inputValue, setInputValue] = useState(value ?? ''); |
| 44 | + const [inputValue, setInputValue] = useState(value); |
45 | 45 |
|
| 46 | + // Update local state when controlled value changes |
46 | 47 | useEffect(() => { |
47 | | - if (value !== undefined && value !== inputValue) { |
| 48 | + if (value !== inputValue) { |
48 | 49 | setInputValue(value); |
49 | 50 | } |
50 | 51 | // eslint-disable-next-line react-hooks/exhaustive-deps |
51 | 52 | }, [value]); |
52 | 53 |
|
53 | | - useEffect(() => { |
54 | | - const handler = debounce((newValue: string) => { |
55 | | - if (onChange) { |
56 | | - const syntheticEvent = { |
57 | | - target: { value: newValue }, |
58 | | - persist: () => {} |
59 | | - } as React.ChangeEvent<HTMLInputElement>; |
| 54 | + // Create synthetic event helper |
| 55 | + const createSyntheticEvent = (value: string): React.ChangeEvent<HTMLInputElement> => |
| 56 | + ({ |
| 57 | + target: { value }, |
| 58 | + persist: () => {} |
| 59 | + }) as React.ChangeEvent<HTMLInputElement>; |
60 | 60 |
|
61 | | - onChange(syntheticEvent); |
62 | | - } |
63 | | - }, debounceTime); |
| 61 | + // Memoize the debounced handler |
| 62 | + const debouncedOnChange = useMemo( |
| 63 | + () => |
| 64 | + debounce((newValue: string) => { |
| 65 | + onChange?.(createSyntheticEvent(newValue)); |
| 66 | + }, debounceTime), |
| 67 | + [onChange, debounceTime] |
| 68 | + ); |
64 | 69 |
|
65 | | - handler(inputValue); |
| 70 | + useEffect(() => { |
| 71 | + if (!onChange) return; |
| 72 | + if (inputValue === '') { |
| 73 | + onChange(createSyntheticEvent(inputValue)); |
| 74 | + } else { |
| 75 | + debouncedOnChange(inputValue); |
| 76 | + } |
66 | 77 |
|
67 | 78 | return () => { |
68 | | - handler.cancel(); |
| 79 | + debouncedOnChange.cancel(); |
69 | 80 | }; |
70 | | - }, [inputValue, onChange, debounceTime]); |
| 81 | + }, [inputValue, onChange, debouncedOnChange]); |
71 | 82 |
|
72 | 83 | const handleChange = (event: React.ChangeEvent<HTMLInputElement>) => { |
73 | | - setInputValue(event.target.value); |
| 84 | + const newValue = event.target.value; |
| 85 | + setInputValue(newValue); |
74 | 86 | }; |
75 | 87 |
|
76 | 88 | return ( |
|
0 commit comments