@@ -33,10 +33,23 @@ interface iProps {
33
33
export const FileUpload = React . forwardRef < HTMLButtonElement , ( iProps ) > ( ( props , ref ) => {
34
34
const classes = useStyles ( ) ;
35
35
const hiddenFileInput = React . useRef ( null ) ;
36
+ const onChangeRef = React . useRef ( props . onChange ) ;
37
+ const asBase64Ref = React . useRef ( props . asBase64 ) ;
38
+
36
39
const isMulti = props . allowMultiple === true ;
37
40
const icon = props . icon || < ArrowUploadRegular /> ;
38
41
const title = isNotEmptyString ( props . title ) ? props . title : `Drop or select ${ isMulti ? 'files' : 'file' } ` ;
39
42
43
+ //keep onChange up to date
44
+ React . useEffect ( ( ) => {
45
+ onChangeRef . current = props . onChange ;
46
+ } , [ props . onChange ] ) ;
47
+ //keep onChange up to date
48
+ React . useEffect ( ( ) => {
49
+ asBase64Ref . current = props . asBase64 ;
50
+ } , [ props . asBase64 ] ) ;
51
+
52
+
40
53
const onGotFiles = React . useCallback ( async ( rawFiles : FileList ) => {
41
54
let errors : string [ ] = [ ] ;
42
55
let acceptedFiles : File [ ] = [ ] ;
@@ -66,18 +79,14 @@ export const FileUpload = React.forwardRef<HTMLButtonElement, (iProps)>((props,
66
79
}
67
80
68
81
if ( isMulti ) {
69
- if ( isFunction ( props . onChange ) ) {
70
- props . onChange ( acceptedFiles , errors ) ;
71
- }
82
+ onChangeRef . current ?.( acceptedFiles , errors ) ;
72
83
}
73
84
else {
74
85
const fileUploaded = acceptedFiles [ 0 ] ;
75
- if ( isFunction ( props . onChange ) ) {
76
- props . onChange ( fileUploaded , errors ) ;
77
- }
86
+ onChangeRef . current ?.( fileUploaded , errors ) ;
78
87
}
79
88
80
- if ( isFunction ( props . asBase64 ) ) {
89
+ if ( isFunction ( asBase64Ref . current ) ) {
81
90
const filesAs64 : base64Result [ ] = [ ] ;
82
91
for ( let i = 0 ; i < ( isMulti ? acceptedFiles . length : 1 ) ; i ++ ) {
83
92
const currentFile = acceptedFiles [ i ] ;
@@ -95,7 +104,7 @@ export const FileUpload = React.forwardRef<HTMLButtonElement, (iProps)>((props,
95
104
else errors . push ( `Could not read file ${ acceptedFiles [ i ] . name } ` ) ;
96
105
}
97
106
}
98
- props . asBase64 ( filesAs64 , errors ) ;
107
+ asBase64Ref . current ?. ( filesAs64 , errors ) ;
99
108
}
100
109
} , useEffectOnlyOnMount ) ;
101
110
0 commit comments