@@ -6,9 +6,11 @@ import {
6
6
Button ,
7
7
} from '@mui/material' ;
8
8
import { ReportType } from '@/context/ReportContext' ;
9
- import api from '../../services/api' ;
10
9
11
10
import './index.scss' ;
11
+ import { useDebounce } from 'use-debounce' ;
12
+ import { useSnackbar } from 'notistack' ;
13
+ import api from '../../services/api' ;
12
14
13
15
type ReportAutocompleteProps = {
14
16
defaultValue ?: ReportType ;
@@ -24,20 +26,44 @@ const ReportAutocomplete = ({
24
26
const [ options , setOptions ] = useState ( [ ] ) ;
25
27
const [ loading , setLoading ] = useState ( false ) ;
26
28
const [ value , setValue ] = useState < ReportType > ( null ) ;
29
+ const [ text , setText ] = useState < string > ( defaultValue ?. patientId || '' ) ;
30
+ const [ debouncedText ] = useDebounce ( text , 500 ) ;
31
+ const snackbar = useSnackbar ( ) ;
27
32
28
33
useEffect ( ( ) => {
29
34
if ( defaultValue ) {
30
35
setValue ( defaultValue ) ;
31
36
}
32
37
} , [ defaultValue ] ) ;
33
38
34
- const handleInputChange = async ( { target : { value : queryValue } } ) => {
35
- setLoading ( true ) ;
36
- const autocompleted = await api . get ( `/reports?searchText=${ queryValue } ` , { } ) . request ( ) ;
39
+ useEffect ( ( ) => {
40
+ setText ( ( prevVal ) => {
41
+ if ( ! value ?. patientId ) { return '' ; }
42
+ if ( prevVal !== value ?. patientId ) { return value ?. patientId ; }
43
+ return prevVal ;
44
+ } ) ;
45
+ } , [ value ?. patientId ] ) ;
46
+
47
+ useEffect ( ( ) => {
48
+ const getData = async ( ) => {
49
+ try {
50
+ setLoading ( true ) ;
51
+ const reportsResp = await api . get ( `/reports?searchText=${ debouncedText } ` ) . request ( ) ;
52
+ setOptions ( reportsResp . reports ) ;
53
+ } catch ( e ) {
54
+ snackbar . enqueueSnackbar ( 'Error getting report autocomplete data' ) ;
55
+ } finally {
56
+ setLoading ( false ) ;
57
+ }
58
+ } ;
59
+ if ( debouncedText ) {
60
+ getData ( ) ;
61
+ }
62
+ } , [ snackbar , debouncedText ] ) ;
37
63
38
- setOptions ( autocompleted . reports ) ;
39
- setLoading ( false ) ;
40
- } ;
64
+ const handleTextChange = useCallback ( ( { target : { value : nextText } } ) => {
65
+ setText ( ( prevText ) => ( prevText === nextText ? prevText : nextText ) ) ;
66
+ } , [ ] ) ;
41
67
42
68
const handleSubmit = useCallback ( async ( ) => {
43
69
onSubmit ( value ) ;
@@ -58,7 +84,7 @@ const ReportAutocomplete = ({
58
84
label = { label || 'Report' }
59
85
variant = "outlined"
60
86
margin = "normal"
61
- onChange = { handleInputChange }
87
+ onChange = { handleTextChange }
62
88
InputProps = { {
63
89
...params . InputProps ,
64
90
endAdornment : (
0 commit comments