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 ?

4
  • 1
    Single page apps shouldn’t reload the whole page, just if you don’t want to hard-resets your state. Commented Nov 18, 2017 at 17:23
  • 2
    its not a single page app. Commented Nov 18, 2017 at 17:28
  • @learning_vba You don't need renderTable(); in your MainHandler.js Because that'll be handled by Dashboard.js independently. Commented Nov 18, 2017 at 19:04
  • thing is I dont want to change the existing logic. Is there anyway to detect browser refresh? Commented Nov 19, 2017 at 0:42

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

what do you think about componentDidMount in the top level component? (to detect reload)
@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.
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

Comments

-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");
  }
}

1 Comment

this API is deprecated

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.