|
|
|
@ -4,6 +4,7 @@ import useIsFirstRender from './useIsFirstRender'; |
|
|
|
|
|
|
|
|
|
const useCookieJar = (): { |
|
|
|
|
cookieJar: CookieJar; |
|
|
|
|
buildCookieJar: () => CookieJar; |
|
|
|
|
getCookie: <T>(key: string) => T | undefined; |
|
|
|
|
getSession: () => SessionCookie | undefined; |
|
|
|
|
getSessionUser: () => SessionCookieUser | undefined; |
|
|
|
@ -12,25 +13,10 @@ const useCookieJar = (): { |
|
|
|
|
|
|
|
|
|
const [cookieJar, setCookieJar] = useState<CookieJar>({}); |
|
|
|
|
|
|
|
|
|
const getCookie = useCallback( |
|
|
|
|
<T>(key: string, prefix = 'suiapi.') => |
|
|
|
|
cookieJar[`${prefix}${key}`] as T | undefined, |
|
|
|
|
[cookieJar], |
|
|
|
|
); |
|
|
|
|
|
|
|
|
|
const getSession = useCallback( |
|
|
|
|
() => getCookie<SessionCookie>('session'), |
|
|
|
|
[getCookie], |
|
|
|
|
); |
|
|
|
|
|
|
|
|
|
const getSessionUser = useCallback(() => getSession()?.user, [getSession]); |
|
|
|
|
|
|
|
|
|
useEffect(() => { |
|
|
|
|
if (isFirstRender) { |
|
|
|
|
const buildCookieJar = useCallback(() => { |
|
|
|
|
const lines = document.cookie.split(/\s*;\s*/); |
|
|
|
|
|
|
|
|
|
setCookieJar( |
|
|
|
|
lines.reduce<CookieJar>((previous, line) => { |
|
|
|
|
const jar = lines.reduce<CookieJar>((previous, line) => { |
|
|
|
|
const [key, value] = line.split('=', 2); |
|
|
|
|
|
|
|
|
|
const decoded = decodeURIComponent(value); |
|
|
|
@ -50,13 +36,33 @@ const useCookieJar = (): { |
|
|
|
|
previous[key] = result; |
|
|
|
|
|
|
|
|
|
return previous; |
|
|
|
|
}, {}), |
|
|
|
|
}, {}); |
|
|
|
|
|
|
|
|
|
return jar; |
|
|
|
|
}, []); |
|
|
|
|
|
|
|
|
|
const getCookie = useCallback( |
|
|
|
|
<T>(key: string, prefix = 'suiapi.') => |
|
|
|
|
cookieJar[`${prefix}${key}`] as T | undefined, |
|
|
|
|
[cookieJar], |
|
|
|
|
); |
|
|
|
|
|
|
|
|
|
const getSession = useCallback( |
|
|
|
|
() => getCookie<SessionCookie>('session'), |
|
|
|
|
[getCookie], |
|
|
|
|
); |
|
|
|
|
|
|
|
|
|
const getSessionUser = useCallback(() => getSession()?.user, [getSession]); |
|
|
|
|
|
|
|
|
|
useEffect(() => { |
|
|
|
|
if (isFirstRender) { |
|
|
|
|
setCookieJar(buildCookieJar()); |
|
|
|
|
} |
|
|
|
|
}, [isFirstRender]); |
|
|
|
|
}, [buildCookieJar, isFirstRender]); |
|
|
|
|
|
|
|
|
|
return { |
|
|
|
|
cookieJar, |
|
|
|
|
buildCookieJar, |
|
|
|
|
getCookie, |
|
|
|
|
getSession, |
|
|
|
|
getSessionUser, |
|
|
|
|