Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
September 9, 2021 10:48 am GMT

Some useful custom utility functions for cookie handling in javascript

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=/";}

2. getCookie

// get a cookie and Its valueexport 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 "";}

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;}

How you find it useful


Original Link: https://dev.to/rajeshroyal/some-useful-custom-utility-functions-for-cookie-handling-in-javascript-col

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To