Saturday, 28 August 2021

Execute code on Back Button Click (REACTJS)

Below code is execute when I browse one page to another page for example. when I click on a product from the category page listing, the below code sets a session storage key that will have a position of the category page (how much page has been scrolled).

So when the product page will open it saves its key in session & if again it visited the same category page it restore the page position.

I am trying to make this code save only one session key & remove the previously saved session key regardless of which page the user clicks on the website (i.e category page, product page).

CategoryPage.js

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

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

 React.useEffect(() => {
   var pathName = document.location.pathname.substr(1);
   if (window && sessionStorage.getItem("scrollPosition_"+pathName)) {
     $(window).scrollTop(sessionStorage.getItem('scrollPosition_'+ pathName));
     console.log('position_set to = ' + sessionStorage.getItem('scrollPosition_'+ pathName));
   }
 }, []);

any thoughts on this to remove the previous session key?



from Execute code on Back Button Click (REACTJS)

No comments:

Post a Comment