3

Some useful custom utility🛠 functions for cookie handling in javascript

 3 years ago
source link: https://dev.to/rajeshroyal/some-useful-custom-utility-functions-for-cookie-handling-in-javascript-col
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client
Cover image for Some useful custom utility🛠 functions for cookie handling in javascript

Some useful custom utility🛠 functions for cookie handling in javascript

Sep 9

・1 min read

For a simple cookie operation I prefer to have my own custom functions(obviously from google) instead of using a cookie library in React.js

1. setCookie

// setCookie("cookiename", cookieExist, COOKIE_EXPIRY_TIME);
// example - setCookie("username", cookieExist, (0.5 * 60 * 1000)); this cookie expires in 30 seconds.
// the cookie expiry time have to be in seconds so convert your time in seconds and after that pass it.

export function setCookie(cname, cvalue, exdays) {
    const d = new Date();
    d.setTime(d.getTime() + exdays);
    let expires = "expires=" + d.toGMTString();
    document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}
Enter fullscreen modeExit fullscreen mode

2. getCookie

// get a cookie and Its value
export function getCookie(cname) {
    let name = cname + "=";
    let decodedCookie = decodeURIComponent(document.cookie);
    let ca = decodedCookie.split(';');
    for (let i = 0; i < ca.length; i++) {
        let c = ca[i];
        while (c.charAt(0) == ' ') {
            c = c.substring(1);
        }
        if (c.indexOf(name) == 0) {
            return c.substring(name.length, c.length);
        }
    }
    return "";
}
Enter fullscreen modeExit fullscreen mode

3. checkCookie

// pass the name of the cookie as string which you want to check that if It exists or not.
export function checkCookie(cookiename) {
    let cookieExist = getCookie(cookiename);
    if (cookieExist != "") {
        return cookieExist;
    }
    return false;
}
Enter fullscreen modeExit fullscreen mode

How you find it useful 🙂🙂


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK