Skip to content

Instantly share code, notes, and snippets.

@passosleo
Created July 12, 2024 13:01
Show Gist options
  • Save passosleo/7e0c50ed448dd17b52495d6439c2f7e6 to your computer and use it in GitHub Desktop.
Save passosleo/7e0c50ed448dd17b52495d6439c2f7e6 to your computer and use it in GitHub Desktop.
useCookies
export function useCookies() {
function setCookie<T>(
key: string,
value: T,
expirationDate: Date | null = null,
path = "/"
) {
try {
if (typeof document !== "undefined") {
let cookieString = `${key}=${encodeURIComponent(
JSON.stringify(value)
)}`;
if (expirationDate !== null) {
let cookieExpirationDate = new Date(expirationDate);
cookieExpirationDate.setDate(
cookieExpirationDate.getDate() + expirationDate.getDate()
);
cookieString += `; expires=${cookieExpirationDate.toUTCString()}`;
cookieString += `; path=${path}`;
}
document.cookie = cookieString;
return true;
}
return false;
} catch {
return false;
}
}
function getCookie<T>(key: string): T | null {
try {
if (typeof document !== "undefined") {
const cookies = document.cookie
.split(";")
.map((cookie) => cookie.trim());
for (const cookie of cookies) {
const [cookieKey, cookieValue] = cookie.split("=");
if (cookieKey === key) {
return JSON.parse(decodeURIComponent(cookieValue));
}
}
}
return null;
} catch {
return null;
}
}
function invalidateCookie(key: string) {
try {
if (typeof document !== "undefined") {
document.cookie = `${key}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;`;
return true;
}
return false;
} catch {
return false;
}
}
return { setCookie, getCookie, invalidateCookie };
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment