fix: Let upload-input also accept non-async-change-callbacks

Signed-off-by: Tilman Vatteroth <git@tilmanvatteroth.de>
This commit is contained in:
Tilman Vatteroth 2022-08-21 12:42:42 +02:00
parent d4493aed95
commit ccbbaeb843
2 changed files with 12 additions and 10 deletions

View file

@ -36,7 +36,6 @@ export const UploadImageButton: React.FC = () => {
.map((state) => extractSelectedText(state)) .map((state) => extractSelectedText(state))
.orElse(undefined) .orElse(undefined)
handleUpload(file, undefined, description) handleUpload(file, undefined, description)
return Promise.resolve()
}, },
[codeMirror, handleUpload] [codeMirror, handleUpload]
) )

View file

@ -13,7 +13,7 @@ import { cypressId } from '../../../utils/cypress-attribute'
const log = new Logger('UploadInput') const log = new Logger('UploadInput')
export interface UploadInputProps extends PropsWithDataCypressId { export interface UploadInputProps extends PropsWithDataCypressId {
onLoad: (file: File) => Promise<void> onLoad: (file: File) => Promise<void> | void
allowedFileTypes: string allowedFileTypes: string
onClickRef: MutableRefObject<(() => void) | undefined> onClickRef: MutableRefObject<(() => void) | undefined>
} }
@ -33,19 +33,22 @@ export const UploadInput: React.FC<UploadInputProps> = ({ onLoad, allowedFileTyp
}, []) }, [])
const onChange = useCallback<React.ChangeEventHandler<HTMLInputElement>>( const onChange = useCallback<React.ChangeEventHandler<HTMLInputElement>>(
(event) => { async (event) => {
const fileInput = event.currentTarget const fileInput = event.currentTarget
if (!fileInput.files || fileInput.files.length < 1) { if (!fileInput.files || fileInput.files.length < 1) {
return return
} }
const file = fileInput.files[0] const file = fileInput.files[0]
onLoad(file) try {
.then(() => { const loadResult = onLoad(file)
fileInput.value = '' if (loadResult instanceof Promise) {
}) await loadResult
.catch((error: Error) => { }
log.error('Error while uploading file', error) } catch (error) {
}) log.error('Error while uploading file', error)
} finally {
fileInput.value = ''
}
}, },
[onLoad] [onLoad]
) )