2

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 ?

learning_vba
  • 360
  • 2
  • 3
  • 14

3 Answers3

5

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.

Darryl RN
  • 7,432
  • 4
  • 26
  • 46
Dez
  • 5,702
  • 8
  • 42
  • 51
  • what do you think about componentDidMount in the top level component? (to detect reload) – Giorgi Moniava Jan 29 '19 at 12:46
  • @giorgim I have been trying it and besides it is better to use the `beforeunload` event listener, indeed it is more reliable to apply the logic in `componentDidMount`. – Dez Jan 31 '19 at 07:25
0

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

Roshith R
  • 31
  • 2
-1

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");
  }
}
GunarathneMDD
  • 180
  • 1
  • 2
  • 11