6 changed files with 219 additions and 141 deletions
@ -1,35 +1,52 @@ |
|||||
import React from "react"; |
|
||||
import Cookies, { type CookieAttributes } from "js-cookie"; |
import Cookies, { type CookieAttributes } from "js-cookie"; |
||||
|
import { useCallback, useState } from "react"; |
||||
|
|
||||
type Cookie<T> = [ |
interface CookieHookResult<T> { |
||||
T | undefined, |
value: T | undefined; |
||||
(value: T, options?: CookieAttributes) => void, |
setCookie: (value: T, options?: CookieAttributes) => void; |
||||
() => void, |
removeCookie: () => void; |
||||
]; |
} |
||||
|
|
||||
const useCookie = <T>( |
function useCookie<T extends object>( |
||||
cookieName: string, |
cookieName: string, |
||||
initialValue?: T, |
initialValue?: T, |
||||
): Cookie<T> => { |
): CookieHookResult<T> { |
||||
const [cookieValue, setCookieValue] = React.useState<T | undefined>(() => { |
const [cookieValue, setCookieValue] = useState<T | undefined>(() => { |
||||
const cookie = Cookies.get(cookieName); |
try { |
||||
return cookie ? (JSON.parse(cookie) as T) : initialValue; |
const cookie = Cookies.get(cookieName); |
||||
|
return cookie ? (JSON.parse(cookie) as T) : initialValue; |
||||
|
} catch (error) { |
||||
|
console.error(`Error parsing cookie ${cookieName}:`, error); |
||||
|
return initialValue; |
||||
|
} |
||||
}); |
}); |
||||
|
|
||||
const setCookie = React.useCallback( |
const setCookie = useCallback( |
||||
(value: T, options?: CookieAttributes) => { |
(value: T, options?: CookieAttributes) => { |
||||
Cookies.set(cookieName, JSON.stringify(value), options); |
try { |
||||
setCookieValue(value); |
Cookies.set(cookieName, JSON.stringify(value), options); |
||||
|
setCookieValue(value); |
||||
|
} catch (error) { |
||||
|
console.error(`Error setting cookie ${cookieName}:`, error); |
||||
|
} |
||||
}, |
}, |
||||
[cookieName], |
[cookieName], |
||||
); |
); |
||||
|
|
||||
const removeCookie = React.useCallback(() => { |
const removeCookie = useCallback(() => { |
||||
Cookies.remove(cookieName); |
try { |
||||
setCookieValue(undefined); |
Cookies.remove(cookieName); |
||||
|
setCookieValue(undefined); |
||||
|
} catch (error) { |
||||
|
console.error(`Error removing cookie ${cookieName}:`, error); |
||||
|
} |
||||
}, [cookieName]); |
}, [cookieName]); |
||||
|
|
||||
return [cookieValue, setCookie, removeCookie]; |
return { |
||||
}; |
value: cookieValue, |
||||
|
setCookie, |
||||
|
removeCookie, |
||||
|
}; |
||||
|
} |
||||
|
|
||||
export default useCookie; |
export default useCookie; |
||||
|
|||||
Loading…
Reference in new issue