Incrementing Cookie Value in Javascript Each Refresh

I am having an issue where I want a value of my cookie to increase by 1 each time I load the page. Currently, I can get the value to go up by 1, but since the values variable is called at the beginning it continues to reset each visit.

var cName = "Cookie Value";
var cValue = 0, expDays = 10;
let cookies = document.cookie;
        
function buildCookie(cName, cValue, expDays) {
    let date = new Date();
    date.setTime(date.getTime() + (expDays * 24 * 60 * 60 * 1000));
    const expires = "expires=" + date.toUTCString();
    document.cookie = cName + "=" + cValue + "; " + expires + "; path=/";
}

function setToZero() {
    buildCookie(cName, cValue=0, expDays);
    console.log('Cookie set to 0');
}

function wholePackage() {
    if (cookies == null) {
        setToZero();
    } else {
        if (cValue >= 0) {
            cValue = cValue + 1;
            buildCookie(cName, cValue, expDays);
            console.log('Cookie to set to ' + cValue);
        }
    }
}

wholePackage()

Any help would be appreciated, thank you.



Read more here: https://stackoverflow.com/questions/68487470/incrementing-cookie-value-in-javascript-each-refresh

Content Attribution

This content was originally published by wolfnid at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: