( key: string, initialValue: T, opts?: Cookies.CookieAttributes, )
| 2 | import { useEffect, useState } from "react"; |
| 3 | |
| 4 | export function useCookies<T>( |
| 5 | key: string, |
| 6 | initialValue: T, |
| 7 | opts?: Cookies.CookieAttributes, |
| 8 | ): [T, (value: T) => void] { |
| 9 | const [storedValue, setStoredValue] = useState<T>(() => { |
| 10 | // Retrieve from Cookies |
| 11 | const item = Cookies.get(key); |
| 12 | return item ? JSON.parse(item) : initialValue; |
| 13 | }); |
| 14 | |
| 15 | useEffect(() => { |
| 16 | // Update state if the cookie changes |
| 17 | const handleStorageChange = () => { |
| 18 | const item = Cookies.get(key); |
| 19 | if (item) { |
| 20 | setStoredValue(JSON.parse(item)); |
| 21 | } |
| 22 | }; |
| 23 | |
| 24 | // Add listener for storage changes |
| 25 | window.addEventListener("storage", handleStorageChange); |
| 26 | |
| 27 | // Cleanup |
| 28 | return () => { |
| 29 | window.removeEventListener("storage", handleStorageChange); |
| 30 | }; |
| 31 | }, [key]); |
| 32 | |
| 33 | const setValue = (value: T) => { |
| 34 | // Save state |
| 35 | setStoredValue(value); |
| 36 | // Save to Cookies |
| 37 | Cookies.set(key, JSON.stringify(value), opts); |
| 38 | }; |
| 39 | |
| 40 | return [storedValue, setValue]; |
| 41 | } |
no test coverage detected
searching dependent graphs…