javascriptreactjsbrowserpage-refresh

How to detec if browser was reload - React/Typescript


Can you help, please?

I'm trying a way for detec if browser was reload and the most answers about this say something like

const typeOfNavigation = (performance.getEntriesByType("navigation")[0] as PerformanceNavigationTiming).type
        
 if(typeOfNavigation === 'reload'){
   localStorage.removeItem('products-list');          
 }

The problem is that the code above since user make refresh the browser , the type is always stay like "reload" and that Api does not exist method for refresh or clear to "navigation", Ideally, it would return to its original state. "navigate", but that doesn't happen, So I need that something dinamic.

I found the code above, work perfect for me , but is deprecated

if(window.event?.type === "loadend"){
   localStorage.removeItem('products-list')
}

In short, Can someone help me about that question , any idea is welcome, I need know each time when the user make refresh the browser through f5 or clicking the button,

Obs: I'm using React/Typescript

Thanks in advance


Solution

  • You can listen for the beforeunload event. This event is fired when the user navigates away from the page, closes the window/tab, or reloads the page. Documentation.