0

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

Deoxys_0
  • 65
  • 7
  • 1
    You should spend a small amount of time looking into web workers, if you spawn a worker you can continue the upload as long as the tab is open, however if the user closes the tab there is nothing you can do to continue. A combination of warning the user when the tab closes https://stackoverflow.com/questions/10311341/confirmation-before-closing-of-tab-browser and web workers may get the result you're after. – Daniel Tate Jun 22 '23 at 19:36
  • https://stackoverflow.com/questions/11844256/alert-for-unsaved-changes-in-form – makeitmorehuman Jun 22 '23 at 19:39

0 Answers0