Skip to content

Commit

Permalink
fix: replace FileReader with URL.createObjectURL (GetStream#1701)
Browse files Browse the repository at this point in the history
  • Loading branch information
arnautov-anton authored Aug 16, 2022
1 parent 565ee55 commit c8a490e
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 27 deletions.
8 changes: 7 additions & 1 deletion src/components/MessageInput/hooks/useAttachments.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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' });
}
Expand Down
35 changes: 9 additions & 26 deletions src/components/MessageInput/hooks/useImageUploads.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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 {
Expand Down

0 comments on commit c8a490e

Please sign in to comment.