I have a component like:
import React, { PropTypes, Component } from 'react'
class MyView extends Component {
componentDidMount() {
window.addEventListener('onbeforeunload', this.saveState())
}
componentWillUnmount() {
window.removeEventListener('beforeunload', this.saveState())
}
saveState() {
alert("exiting")
}
render() {
return (
<div>
Something
</div>
)
}
}
export default MyView
Here when a user refresh the page I want to call a specific funtion and when call is finished I want the page to be refreshed. Same when user closes the page.
In my above code I am adding an event listener onbeforeunload
and calling a saveState
function.
But here my componentDidMount
is working normally. onbeforeunload
and saveState
function is called normally when page is loaded not when page is refreshed or exited.
What is wrong in here and how can I call specific funcitn or give alert when someone exits or refresh the page in react ?
In the above code
Attach beforeunload event on top level component and on beforeunload event make render empty which will trigger componentWillUnmount of all child components.
import React, { PropTypes, Component } from 'react'
class App extends Component {
componentDidMount() {
window.addEventListener('beforeunload', () =>{
this.setState({appended:true});
});
}
render() {
if(this.state.appended){
return false;
}else{
return (<MyView />)
}
}
}
class MyView extends Component {
componentWillUnmount() {
this.saveState()
}
saveState() {
alert("exiting")
}
render() {
return (
<div>
Something
</div>
)
}
}
export default MyView
Hope this work for you.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With