DEV Community

Discussion on: JavaScript Cookies

Collapse
lukeshiru profile image
LUKESHIRU

2 things:

  • Nowadays, pretty much any webapp has readonly cookies. This means that the cookies are set in the server side and you can't change them from the client side, so ideally if you want to save data in the client side, you should use localStorage, which is way better suited for this task.
  • You can simplify your function to get cookies, and this way you'll not need stuff like checkCookie, here it is:
// Let's say you have this in your cookies:
// foo=1; bar=2

const cookies = Object.fromEntries(
    document.cookie.split("; ").map(cookie => cookie.split("=")),
);

// cookies now has an object with each property representing a value in your cookies:
cookies.foo === 1; // 🎉
cookies.bar === 2; // 🎉
Enter fullscreen mode Exit fullscreen mode

The code above simply takes document.cookie, splits that using the "; " string, and then we map over it splitting every key/value using the equal sign, so we get an array of tuples [key, value], finally we use Object.fromEntries to turn that array of entries into an object.

Cheers!