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}`);
}
}, []);
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.