Advertisement
Devanshu-bot

Untitled

Jul 31st, 2024 (edited)
528
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
TypeScript 1.72 KB | Source Code | 0 0
  1. import { useState, useEffect, useCallback } from "react";
  2.  
  3. interface CookieOptions {
  4.   expires?: number;
  5.   maxAge?: number;
  6.   domain?: string;
  7.   path?: string;
  8.   secure?: boolean;
  9.   httpOnly?: boolean;
  10.   sameSite?: "Strict" | "Lax" | "None";
  11. }
  12.  
  13. const useCookie = (key: string, options: CookieOptions = {}) => {
  14.   const [value, setValue] = useState<string | null>(null);
  15.  
  16.   const getCookieValue = useCallback(() => {
  17.     const name = `${key}=`;
  18.     const decodedCookie = decodeURIComponent(document.cookie);
  19.     const ca = decodedCookie.split("; ");
  20.     for (let i = 0; i < ca.length; i++) {
  21.       let c = ca[i];
  22.       if (c.indexOf(name) === 0) {
  23.         return c.substring(name.length, c.length);
  24.       }
  25.     }
  26.     return null;
  27.   }, [key]);
  28.  
  29.   const setCookie = (value: string, options: CookieOptions = {}) => {
  30.     let cookie = `${key}=${encodeURIComponent(value)}`;
  31.     const { expires, maxAge, domain, path, secure, httpOnly, sameSite } = options;
  32.  
  33.     if (expires) {
  34.       const date = new Date();
  35.       date.setTime(date.getTime() + expires * 1000);
  36.       cookie += `; Expires=${date.toUTCString()}`;
  37.     }
  38.  
  39.     if (maxAge) cookie += `; Max-Age=${maxAge}`;
  40.     if (domain) cookie += `; Domain=${domain}`;
  41.     if (path) cookie += `; Path=${path}`;
  42.     if (secure) cookie += "; Secure";
  43.     if (httpOnly) cookie += "; HttpOnly";
  44.     if (sameSite) cookie += `; SameSite=${sameSite}`;
  45.  
  46.     document.cookie = cookie;
  47.     setValue(getCookieValue());
  48.   };
  49.  
  50.   const clearCookie = () => {
  51.     setCookie("", { ...options, expires: -1 });
  52.   };
  53.  
  54.   useEffect(() => {
  55.     setValue(getCookieValue());
  56.   }, [key, getCookieValue]);
  57.  
  58.   return [value, setCookie, clearCookie] as const;
  59. };
  60.  
  61. export { useCookie };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement