Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Refresh the page only once in react class component

I have a react app with a page with a class component on it. What I want to do is to refresh that page only once when you first load it, but all that I have tried, with window.location.reload() for example, ends up in a infinite refresh loop. Does anyone know how to do this? I a functional component I do like this, and it works :

 useEffect(() => {
    if(reloadCount < 2) {
      sessionStorage.setItem('reloadCount', String(reloadCount + 1));
      window.location.reload();
    } else {
      sessionStorage.removeItem('reloadCount');
    }
  }, []);

but if I convert it for class component, like this, it doesn't work :

componentDidMount() {
    if(this.reloadCount < 2) {
      sessionStorage.setItem('reloadCount', String(this.reloadCount + 1));
      window.location.reload();
    } else {
      sessionStorage.removeItem('reloadCount');
    }
  }

Any idea how to do this in react class components ?

P.S. I want to do this because I use a mapbox component that saves the previously initialized map to the DOM, so when the user return to the page containing the map, there's no need to initialize the map again. But now I have this map on another page too, and if I navigate between the 2 pages containing the map, it keeps the css from the previous page, and it's messed up. And the only way I can work around this is to force refresh the page.

like image 876
Bogos Robert Avatar asked Oct 19 '25 15:10

Bogos Robert


1 Answers

Maybe this will fix your problem

componentDidMount() {
    const reloadCount = sessionStorage.getItem('reloadCount');
    if(reloadCount < 2) {
      sessionStorage.setItem('reloadCount', String(reloadCount + 1));
      window.location.reload();
    } else {
      sessionStorage.removeItem('reloadCount');
    }
  }
like image 101
rommyarb Avatar answered Oct 21 '25 05:10

rommyarb



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!