Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import { useState, useEffect, useCallback } from "react";
- interface CookieOptions {
- expires?: number;
- maxAge?: number;
- domain?: string;
- path?: string;
- secure?: boolean;
- httpOnly?: boolean;
- sameSite?: "Strict" | "Lax" | "None";
- }
- const useCookie = (key: string, options: CookieOptions = {}) => {
- const [value, setValue] = useState<string | null>(null);
- const getCookieValue = useCallback(() => {
- const name = `${key}=`;
- const decodedCookie = decodeURIComponent(document.cookie);
- const ca = decodedCookie.split("; ");
- for (let i = 0; i < ca.length; i++) {
- let c = ca[i];
- if (c.indexOf(name) === 0) {
- return c.substring(name.length, c.length);
- }
- }
- return null;
- }, [key]);
- const setCookie = (value: string, options: CookieOptions = {}) => {
- let cookie = `${key}=${encodeURIComponent(value)}`;
- const { expires, maxAge, domain, path, secure, httpOnly, sameSite } = options;
- if (expires) {
- const date = new Date();
- date.setTime(date.getTime() + expires * 1000);
- cookie += `; Expires=${date.toUTCString()}`;
- }
- if (maxAge) cookie += `; Max-Age=${maxAge}`;
- if (domain) cookie += `; Domain=${domain}`;
- if (path) cookie += `; Path=${path}`;
- if (secure) cookie += "; Secure";
- if (httpOnly) cookie += "; HttpOnly";
- if (sameSite) cookie += `; SameSite=${sameSite}`;
- document.cookie = cookie;
- setValue(getCookieValue());
- };
- const clearCookie = () => {
- setCookie("", { ...options, expires: -1 });
- };
- useEffect(() => {
- setValue(getCookieValue());
- }, [key, getCookieValue]);
- return [value, setCookie, clearCookie] as const;
- };
- export { useCookie };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement