I wanted to calculate the user's session count through session storage and local storage.
- Get the last session value from local storage.
-
- If there is no stored value create new storage items. Session storage prevents increase value in the same session.
- If the last session value is not null, the user was closed browser and opened it again. Increase the last storage value and save the last values.
- Finally it returns session count.
var updateStorages = (storageValue) => {
localStorage.setItem('last-session-value', storageValue);
sessionStorage.setItem('current-session', storageValue);
};
var getSessionCount = () => {
var lastSessionValue = localStorage.getItem('last-session-value');
if (lastSessionValue === null) {
updateStorages(1);
} else if (lastSessionValue && sessionStorage.getItem('current-session') === null) {
lastSessionValue++;
updateStorages(lastSessionValue);
}
return parseInt(lastSessionValue);
};
getSessionCount();
It's my first technical post. It's just basic solution and I wanted to share it. I would like write more complicated things too. Cheers.
Top comments (0)