From c8a490ebc53da03c2b0f064de88c0cb634ed2a70 Mon Sep 17 00:00:00 2001 From: Anton Arnautov <43254280+arnautov-anton@users.noreply.github.com> Date: Wed, 17 Aug 2022 01:36:06 +0200 Subject: [PATCH] fix: replace FileReader with URL.createObjectURL (#1701) --- .../MessageInput/hooks/useAttachments.ts | 8 ++++- .../MessageInput/hooks/useImageUploads.ts | 35 +++++-------------- 2 files changed, 16 insertions(+), 27 deletions(-) diff --git a/src/components/MessageInput/hooks/useAttachments.ts b/src/components/MessageInput/hooks/useAttachments.ts index 97577ce59..f7dae59cd 100644 --- a/src/components/MessageInput/hooks/useAttachments.ts +++ b/src/components/MessageInput/hooks/useAttachments.ts @@ -63,7 +63,13 @@ export const useAttachments = < file.type.startsWith('image/') && !file.type.endsWith('.photoshop') // photoshop files begin with 'image/' ) { - dispatch({ file, id, state: 'uploading', type: 'setImageUpload' }); + dispatch({ + file, + id, + previewUri: URL.createObjectURL?.(file), + state: 'uploading', + type: 'setImageUpload', + }); } else if (file instanceof File && !noFiles) { dispatch({ file, id, state: 'uploading', type: 'setFileUpload' }); } diff --git a/src/components/MessageInput/hooks/useImageUploads.ts b/src/components/MessageInput/hooks/useImageUploads.ts index 3613c6b9f..7d614296c 100644 --- a/src/components/MessageInput/hooks/useImageUploads.ts +++ b/src/components/MessageInput/hooks/useImageUploads.ts @@ -97,8 +97,11 @@ export const useImageUploads = < return; } + if (img.previewUri) URL.revokeObjectURL?.(img.previewUri); + dispatch({ id, + previewUri: undefined, state: 'finished', type: 'setImageUpload', url: response.file, @@ -108,32 +111,12 @@ export const useImageUploads = < ); useEffect(() => { - if (FileReader) { - const upload = Object.values(imageUploads).find( - (imageUpload) => - imageUpload.state === 'uploading' && !!imageUpload.file && !imageUpload.previewUri, - ); - if (upload) { - const { file, id } = upload; - // TODO: Possibly use URL.createObjectURL instead. However, then we need - // to release the previews when not used anymore though. - const reader = new FileReader(); - reader.onload = (event) => { - if (typeof event.target?.result !== 'string') return; - dispatch({ - id, - previewUri: event.target.result, - type: 'setImageUpload', - }); - }; - reader.readAsDataURL((file as unknown) as Blob); - uploadImage(id); - return () => { - reader.onload = null; - }; - } - } - return; + const upload = Object.values(imageUploads).find( + (imageUpload) => imageUpload.state === 'uploading' && imageUpload.file, + ); + if (!upload) return; + + uploadImage(upload.id); }, [imageUploads, uploadImage]); return {