2

I am trying to save a session key when user leaves the page here is the code for it, The use of the code is upon loading a page, you want to:

If this page was the last visited page: load its saved location else remove the last saved location and save it upon scrolling.

 const [scrollPosition, setScrollPosition] = React.useState('');

React.useEffect(() => {
    var pathName = document.location.pathname.substr(1);
    if (window) {
      window.onscroll = function (e) {
        setScrollPosition(window.scrollY);
      };
    }
  }, [scrollPosition]);

  if (typeof window !== "undefined") {
    window.addEventListener('unload', function(event) {
      if(scrollPosition != 0){
        const savedPosition = { position: scrollPosition, pathName };
        sessionStorage.setItem('scrollPosition', JSON.stringify(savedPosition));
      }
    }); 
  }

  React.useEffect(() => {
    var pathName = document.location.pathname.substr(1);
    const lastSavedPosition = JSON.parse(sessionStorage.getItem('scrollPosition'));
    if (window && lastSavedPosition && pathName === lastSavedPosition.pathName) {
       window.scrollTo(0, lastSavedPosition.position);
      console.log(`position_set to = ${lastSavedPosition.position}`);
    }
  }, []);
Apoorva Chikara
  • 8,277
  • 3
  • 20
  • 35

1 Answers1

1

I recommend you using localStorage instead of sessionStorage which is only persistent during one user session. When the user comes back, you won't have data available in the session storage to make it persistent use localStorage.

This thread contains a lot of well drafted answers check it, how to use localStorage and when to use it.

Apoorva Chikara
  • 8,277
  • 3
  • 20
  • 35
  • Thanks for the answer, sessionStorage is suitable for the application that's why i am using it. –  Aug 28 '21 at 08:03
  • Additionally its not about sessionstorage & localstorage its about setting a key into sessionstorage only when user leaves a page. –  Aug 28 '21 at 08:03
  • @devhs why not just return from your useEffect as the `componentWillUnmount` function to set a scroll position? window unload event is when you go to close the browser, not switch views to a different component that tracks scroll positions. I am also in agreement, localStorage will be a more hardened solution – John Ruddell Aug 28 '21 at 08:06
  • Linked question : https://stackoverflow.com/questions/68755669/execute-code-on-back-button-click-reactjs –  Aug 28 '21 at 08:08
  • componentWillUnmount is not working actually with error Syntax error: Unexpected token, expected "," –  Aug 28 '21 at 08:10
  • 1
    when you say: leaves the page- what does it mean? Leaving the webpage or navigating to other parts of the current web app? – Apoorva Chikara Aug 28 '21 at 08:18
  • I mean leaving webpage –  Aug 28 '21 at 08:28
  • Have you tried binding [onbeforeunload](https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onbeforeunload) ? – Apoorva Chikara Aug 28 '21 at 09:37