Skip to content

Instantly share code, notes, and snippets.

@Jerga99
Created July 25, 2021 10:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Jerga99/12fa6b3690991dc080a91b113b23632a to your computer and use it in GitHub Desktop.
Save Jerga99/12fa6b3690991dc080a91b113b23632a to your computer and use it in GitHub Desktop.
import useSWR from 'swr';
import { fetcher } from '@/actions';
import { useEffect, useState } from "react"
function doesHttpOnlyCookieExist(cookiename) {
var d = new Date();
d.setTime(d.getTime() + (1000));
var expires = "expires=" + d.toUTCString();
document.cookie = cookiename + "=new_value;path=/;" + expires;
if (document.cookie.indexOf(cookiename + '=') == -1) {
return true;
} else {
return false;
}
}
export const useGetUser = () => {
const [isMounted, setIsMounted] = useState(false)
const hasAuthCookie = isMounted ?
doesHttpOnlyCookieExist('a0:session') : false;
useEffect(() => setIsMounted(true))
const { data, error, isValidating, ...rest } = useSWR(hasAuthCookie ? '/api/v1/me' : null, fetcher);
return {
data,
error,
loading: isMounted && isValidating,
...rest
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment