0

I want to send the current state value, currentPositionSec to the server, when page refreshed. Since componentWillUnmount won't be called on a refresh of the page, I used beforeunload event.

  componentDidMount () {
    window.addEventListener('beforeunload', this.onUnload)
  }

  componentWillUnmount () {
    window.removeEventListener('beforeunload', this.onUnload)
  }

  onUnload (e) {
    console.log('INSIDE onUnload')
    const { hashedId } = this.props
    const { currentPositionSec } = this.state
    // sends the progress to a server
    emitter.emit(LECTURE_VIDEO_PROGRESS, {
      currentPositionSeconds: currentPositionSec,
      hashedId: hashedId
    })
  }

INSIDE onUnload is printed for a short period of time and the page refreshes, I tried this many times and the progress is only saved once, which is weird. Can we wait the code inside onUnload to execute? when I add this in onUnload method, the progress will be saved, but I don't want the popup to be displayed.

e.preventDefault();
e.returnValue = '';
Henok Tesfaye
  • 8,287
  • 13
  • 47
  • 84
  • What does emitter.emit do? I tried a `fetch` before unload and it works every single time (you can preserve log in network tab of devtools). – HMR Apr 16 '20 at 07:58
  • @HMR it has many nested calls there, can you send me the link for the `fetch`? – Henok Tesfaye Apr 16 '20 at 08:01
  • It emits the data to be saved in the server, to the hight level component. – Henok Tesfaye Apr 16 '20 at 08:02
  • So in Chrome devtools under network you can see activity and you don't see that when you refresh and have `Preserve log` checked? – HMR Apr 16 '20 at 09:47
  • [Here](https://codesandbox.io/s/so-comment-c497c?file=/index.js) is a sandbox and [here](https://c497c.csb.app/) you can open the app. Are you using setTimeout in emitter.emit? – HMR Apr 16 '20 at 09:57
  • @HMR I think It relates with this, https://stackoverflow.com/questions/19457535/why-in-chrome-in-onunload-and-onbeforeunload-is-my-xmlhttprequest-being-cancell. – Henok Tesfaye Apr 17 '20 at 06:58

0 Answers0