I'm trying to cause a confirmation popup window to appear if the user reloads the page OR uses the back button while a file is still uploading. Note that it must be for BOTH cases, not just one (but I'm fine if each case needs its own code).
How would I go about doing this? I'm using a class in React (export class extends React.Component...) so it can't use React functional component hooks.
class FileUploadComponent extends React.Component<Props, State> {
state = {
uploadingFile: false,
};
static contextType = ConfirmationContext;
componentDidMount = async () => {
this.checkForStagedUpdates();
};
componentWillUnmount = () => {};
checkForStagedUpdates = async () => {
.
.
.
};
uploadFile = async (file: File) => {
this.setState({
uploadingFile: true,
});
try {
await uploadUpdateFile(file);
this.props.notify({
type: 'success',
body: 'File uploaded',
});
this.checkForStagedUpdates();
} catch (err) {
console.log(err);
if (err.message.includes('405')) {
this.props.notify({ type: 'error', body: 'Invalid file' });
} else {
this.props.notify({
type: 'error',
body: 'There was a problem uploading the file',
});
}
} finally {
this.setState({ uploadingFile: false });
}
};
.
.
.
}
I know I need to use some sort of window event listener, but when I try adding these in componentDidMount, such as,
window.addEventListener('beforeunload', function (e) {
if (uploading) {
return confirmationMessage;
}
});
they don't trigger when I press the back button, even if I manually set the uploading value to true. Sometimes it works if I reload the page, but this is inconsistent.
I've tried the solutions mentioned in the following, but haven't had any luck yet (they just don't trigger): Warn user before leaving web page with unsaved changes Prevent a user to leave page while a file is uploading