4

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.

Bogos Robert
  • 193
  • 2
  • 9
  • 1
    probably share why you want to do that? And we can share an alternative solution. Because what you are doing is not really a normal way to handle any application. Since react is a client side application, the moment you reload the page you are basically "resetting" the client application – Someone Special Apr 10 '21 at 04:42
  • It's because when the page reloads, ``componentDidMount()`` function is called. In this function you called ``window.location.reload()`` function . So the page will reload again and so on. – BTSM Apr 10 '21 at 04:43
  • I doesn't reload at all – Bogos Robert Apr 10 '21 at 04:46
  • @SomeoneSpecial I edited it – Bogos Robert Apr 10 '21 at 04:49
  • You are using a wrong method to handle your problem. To save state u should use react's useContext, or a Redux store, whether you save it to sessionStorage or not. – Someone Special Apr 10 '21 at 04:57
  • @BogosRobert Check `reloadCount` value. Probably `reloadCount` always has value less than 2. – Surjeet Bhadauriya Apr 10 '21 at 05:24
  • Why are you doing this? What needs to be done? Can you give us more context? – Rem Apr 10 '21 at 05:27

1 Answers1

7

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');
    }
  }
rommyarb
  • 425
  • 3
  • 7