Reputation: 380
I am new to react.js. I have a simple page with table. When I reload the page, state is getting lost. Is there a way to detect the browser refresh ?
Upvotes: 2
Views: 21185
Reputation: 31
With [react-beforeunload][1] you can track the page changes easily
import { useBeforeunload } from 'react-beforeunload'
const App = () => {
const [preventMultiSubmit, setPreventMultiSubmit] = useState(false)
}
const pageRefConf = useBeforeunload((event) => {
if (preventMultiSubmit) {
event.preventDefault()
}
})
useEffect(() => {
window.addEventListener('beforeunload', pageRefConf)
return () => {
window.removeEventListener('beforeunload', pageRefConf)
}
}, [])
This worked for me. I hope this one will work for you too. [1]: https://www.npmjs.com/package/react-beforeunload
Upvotes: 0
Reputation: 5838
The event beforeunload is executed just before window browser is being refreshed. Event is cancellable.
window.beforeunload = (e) => {
console.log('Stop this');
e.preventDefault()
e.returnValue = '';
};
When using React an option is to take control in your Application component, or your most higher order component, in the componentDidMount
lifecycle method as @georgim suggested instead componentWillUnmount
as I first suggested, and manage there what you want to achieve.
Upvotes: 5
Reputation: 180
Try this one. This worked for me.
if (window.performance) {
if (performance.navigation.type == 1) {
alert( "This page is reloaded" );
} else {
alert( "This page is not reloaded");
}
}
Upvotes: -1