I have an application where (amongst other things) a user can upload multiple files to storage. Prior to uploading, I read the file and calculate an MD5 hash. Once a user selects the file(s) for upload, I render a component (SelectedFile) for each file that was selected, passing in the file and an async progress function (which in this case will get the MD5 hash). When this component renders, the progress function starts and progress is displayed.
What I need is to allow the user to cancel the function that is running and remove the file. My implementation seems to work fine when only a single file is selected, but when multiple files are selected, the cancel functionality breaks. I end up getting the following error when I attempt to cancel one of the files (though it seems to happen inconsistently)
index.js:1 Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function. at SelectedFile
I am having a lot of trouble debugging this, but I am at the point where I believe (for whatever reason) that canceling the function in one render of the SelectedFile component, is attempting to update the state of another render of this component. Here is the relevant code:
Here is the component (SelectedFile):
import { useEffect, useRef, useState } from 'react';
import { UploadBlob } from '../../apis/facade';
import {
Card, FormLabel, LinearProgress, IconButton,
} from '@mui/material';
import { CancelOutlined } from '@mui/icons-material';
interface ISelectedFileProps {
file: UploadBlob,
progressFn: (
blob: UploadBlob,
progressCallback: (prog: number) => boolean,
endCallback: (result: string) => void,
onCancel: () => void,
) => Promise<unknown>,
showProgress: boolean,
allowCancel: boolean,
startProgressFn: boolean,
progressFinished: boolean,
loading: boolean,
}
export function SelectedFile(props: ISelectedFileProps) {
const {
file, removeFile, progressFn,
startProgressFn, progressFinished,
showProgress, allowCancel, loading,
} = props;
const [progress, setProgress] = useState<number>(0);
const [cancelProgressFn, setCancelProgressFn] = useState<boolean>(false);
const stopProgressFn = () => {
console.log('PRESSED CANCEL BUTTON', file.name)
setCancelProgressFn(true);
}
// `progressFn` callback cannot access `cancelProgressFn` state
const stateRef = useRef<boolean>(false);
stateRef.current = cancelProgressFn;
useEffect(() => {
if (file) {
if (progressFinished) {
setProgress(100);
} else {
startProgressFn && progressFn(
file,
(prog) => {
setProgress(Math.round(prog * 100) || 0);
return stateRef.current;
},
() => {
setProgress(100)
},
() => {
console.log(`${file.name} removed`)
}
);
}
}
}, [file, startProgressFn, progressFinished]);
return (
<Card className='selected-file'>
<span>
{file.name}
{showProgress &&
<FormLabel
style={{ position: 'absolute', right: 65 }}
>{progress}%</FormLabel>
}
{allowCancel &&
<IconButton
size='small'
color='primary'
onClick={stopProgressFn}
style={{ position: 'absolute', right: 0 }}
disabled={loading}
><CancelOutlined fontSize="inherit" />
</IconButton>
}
</span>
{startProgressFn && <span style={{ width: '90%' }}>
<LinearProgress
variant={showProgress ? 'determinate' : 'indeterminate'}
value={progress}
/>
</span>}
</Card>
)
}
Here is the function (calculateMD5):
const readChunked = (
file: File,
chunkCallback: (chunk: string, offset: number, fileSize: number) => boolean,
endCallback: (err: DOMException | ProgressEvent<FileReader> | null) => void,
onCancel: () => void,
) => {
const fileSize = file.size;
const chunkSize = 4 * 1024 * 1024; // 4MB
let offset = 0;
const reader = new FileReader();
reader.onload = () => {
if (reader.error) {
endCallback(reader.error || {});
return;
} else if (reader.result) {
const result = reader.result as string
offset += result.length;
const end = chunkCallback(result, offset, fileSize);
if (offset >= fileSize) {
endCallback(null);
return;
}
if (end) {
onCancel();
return;
}
}
readNext();
};
reader.onerror = (err) => endCallback(err || {});
const readNext = () => {
const fileSlice = file.slice(offset, offset + chunkSize);
reader.readAsBinaryString(fileSlice);
}
readNext();
}
export async function calculateMD5(
blob: UploadBlob,
progressCallback: (prog: number) => boolean,
endCallback: (hash: string) => void,
onCancel: () => void,
): Promise<string> {
return new Promise((resolve, reject) => {
const md5 = CryptoJS.algo.MD5.create();
readChunked(
blob.originalFile,
(chunk, offset, total) => {
md5.update(CryptoJS.enc.Latin1.parse(chunk));
return progressCallback(offset / total);
},
(err: DOMException | ProgressEvent<FileReader> | null) => {
if (err) {
reject(err);
} else {
const hash = md5.finalize();
const hashBase64 = hash.toString(CryptoJS.enc.Base64);
resolve(hashBase64);
endCallback(hashBase64);
}
},
() => {
onCancel();
}
);
});
}
Here is how I pass it in from the parent component (SelectFiles):
export function SelectFile(props: IStepProps) {
const {
context: {
supportedFiles,
getFileHeaders,
formatMetadata,
},
loading, toggleLoading,
files, updateFiles,
allowStepForward,
} = props;
/* ... */
const updateFile = (fileToUpdate: UploadBlob) => {
const updatedFileList = files.filter((file) => file !== fileToUpdate);
updatedFileList.push(fileToUpdate);
updateFiles(updatedFileList);
}
const onFileSelection = async (targetFiles: FileList | null) => {
toggleLoading(true);
try {
const selectedFiles: UploadBlob[] = await Promise.all(
[...(targetFiles || [])].map(async (file: File) => {
const extension = `.${file.name.split('.').pop()}`;
if (!supportedFiles.includes(extension)) {
throw new Error(`Supported filetypes: ${supportedFiles.join(', ')}`);
}
const fileHeaders = await getFileHeaders(file) as FileHeaders;
const nameWithoutExtension = file.name.split(extension)[0];
const metadata = formatMetadata(nameWithoutExtension, fileHeaders);
return {
originalFile: file,
lastModified: file.lastModified,
size: file.size,
name: file.name,
contentType: file.type,
contentMd5: '',
extension,
fileHeaders,
metadata,
}
})
);
if (inputRef.current) {
inputRef.current.value = '';
}
if (validateFileTypes(selectedFiles, supportedFiles)) {
setErrorMessage('');
updateFiles(selectedFiles);
setOpenDialog(true);
}
} catch (e) {
if (e instanceof Error) {
setErrorMessage(e.message);
}
} finally {
toggleLoading(false);
}
}
const removeFile = (fileToRemove: UploadBlob) => {
const updatedFileList = files.filter((file) => file !== fileToRemove);
updateFiles(updatedFileList);
}
const md5ProgressFn = (
blob: UploadBlob,
progressCallback: (prog: number) => boolean,
endCallback: (result: string) => void,
onCancel: () => void,
) => {
return calculateMD5(
blob,
(prog) => {
return progressCallback(prog)
},
(hash) => {
blob.contentMd5 = hash;
updateFile(blob);
endCallback(hash);
},
() => {
removeFile(blob);
onCancel();
}
)
}
/* ... */
return (
<div style={{ textAlign: 'center' }}>
{errorMessage && <Alert
className='alert select-file-error'
severity='error'
onClose={() => setErrorMessage('')}
>
<AlertTitle>{errorMessage}</AlertTitle>
</Alert>}
{files.length > 0 &&
<Button
onClick={() => setOpenDialog(true)}
className='view-files'
disabled={loading}
>Click here to view {files.length} selected file{files.length === 1 ? '' : 's'}
</Button>
}
<div
{...getRootProps({ className: 'action-div file-upload' })}
>
<div style={{ margin: 'auto' }}>
Drag and drop files here or
<Button
style={{ marginLeft: '5px' }}
disabled={loading}
variant='contained'
component='label'
size='small'
>Browse Files
<input
{...getInputProps()}
ref={inputRef}
type='file'
multiple={true}
accept={supportedFiles.join(',')}
onChange={({ target: { files } }) => files?.length && onFileSelection(files)}
hidden={true}
/>
</Button>
</div>
</div>
<Dialog
open={true}
className='file-dialog'
style={{ visibility: openDialog && files.length ? 'visible' : 'hidden' }}
>
<div>
<IconButton
size='medium'
color='default'
onClick={() => setOpenDialog(false)}
style={{ position: 'absolute', right: 0, top: 0 }}
disabled={loading}
><CancelOutlined fontSize="inherit" />
</IconButton>
<div className='card-container'>
{files.map((file, i) => (
<SelectedFile
key={i}
file={file}
removeFile={removeFile}
progressFn={md5ProgressFn}
showProgress={true}
allowCancel={true}
startProgressFn={true}
progressFinished={!!file.contentMd5}
loading={loading}
/>
))}
</div>
</div>
</Dialog>
</div>
)
}