DEV Community

Emre Erkoca
Emre Erkoca

Posted on

 

Calculating User's Session Count

I wanted to calculate the user's session count through session storage and local storage.

  1. 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.
  2. 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)

This post blew up on DEV in 2020:

js visualized

🚀⚙️ JavaScript Visualized: the JavaScript Engine

As JavaScript devs, we usually don't have to deal with compilers ourselves. However, it's definitely good to know the basics of the JavaScript engine and see how it handles our human-friendly JS code, and turns it into something machines understand! 🥳

Happy coding!