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 = '';