From d6c230ddc830dd3b4519f60ae22723f88bd5a42c Mon Sep 17 00:00:00 2001 From: Olabode Lawal-Shittabey Date: Tue, 25 Jul 2023 21:43:28 +0100 Subject: [PATCH] refactor: merge `authSession` function into `useSession` hook (#1391) Co-authored-by: Brandon Roberts --- .../molecules/AuthSection/auth-section.tsx | 8 +-- .../UserSettingsPage/user-settings-page.tsx | 37 ++++++------- layouts/private-wrapper.tsx | 5 +- lib/hooks/authSession.ts | 24 -------- lib/hooks/useSession.ts | 55 ++++++++++++------- next-types.d.ts | 1 + 6 files changed, 57 insertions(+), 73 deletions(-) delete mode 100644 lib/hooks/authSession.ts diff --git a/components/molecules/AuthSection/auth-section.tsx b/components/molecules/AuthSection/auth-section.tsx index 7deef7a460..44a7c0b9df 100644 --- a/components/molecules/AuthSection/auth-section.tsx +++ b/components/molecules/AuthSection/auth-section.tsx @@ -18,7 +18,6 @@ import Text from "components/atoms/Typography/text"; import GitHubIcon from "img/icons/github-icon.svg"; import Icon from "components/atoms/Icon/icon"; import NotificationCard from "components/atoms/NotificationsCard/notification-card"; -import { authSession } from "lib/hooks/authSession"; import { Spinner } from "components/atoms/SpinLoader/spin-loader"; import { Popover, PopoverContent, PopoverTrigger } from "../Popover/popover"; import DropdownList from "../DropdownList/dropdown-list"; @@ -32,7 +31,7 @@ const AuthSection: React.FC = ({}) => { const currentPath = router.asPath; const { signIn, signOut, user, sessionToken } = useSupabaseAuth(); - const { onboarded } = useSession(); + const { onboarded, session } = useSession(true); const [notifications, setNotifications] = useState([]); const [loading, setLoading] = useState(false); const [userInfo, setUserInfo] = useState(undefined); @@ -65,9 +64,8 @@ const AuthSection: React.FC = ({}) => { useEffect(() => { const getUser = async () => { - const response = await authSession(); - if (response !== false && !userInfo) { - setUserInfo(response); + if (session && !userInfo) { + setUserInfo(session); } }; diff --git a/components/organisms/UserSettingsPage/user-settings-page.tsx b/components/organisms/UserSettingsPage/user-settings-page.tsx index 5c1ec77a1c..95c413e293 100644 --- a/components/organisms/UserSettingsPage/user-settings-page.tsx +++ b/components/organisms/UserSettingsPage/user-settings-page.tsx @@ -15,7 +15,6 @@ import StripeCheckoutButton from "components/organisms/StripeCheckoutButton/stri import { updateUser, UpdateUserPayload } from "lib/hooks/update-user"; import useSession from "lib/hooks/useSession"; -import { authSession } from "lib/hooks/authSession"; import { validateEmail } from "lib/utils/validate-email"; import { timezones } from "lib/utils/timezones"; import { updateEmailPreferences } from "lib/hooks/updateEmailPreference"; @@ -37,7 +36,7 @@ const UserSettingsPage = ({ user }: userSettingsPageProps) => { revalidateOnFocus: false, }); - const { hasReports } = useSession(); + const { hasReports, session } = useSession(true); const { toast } = useToast(); @@ -62,24 +61,22 @@ const UserSettingsPage = ({ user }: userSettingsPageProps) => { const interestArray = getInterestOptions(); useEffect(() => { - async function fetchAuthSession() { - const response = await authSession(); - if (response !== false && !userInfo) { - setUserInfo(response); - formRef.current!.nameInput.value = response.name; - setEmail(response.email); - setDisplayLocalTime(response.displayLocalTime); - formRef.current!.bio.value = response.bio; - formRef.current!.url.value = response.url; - formRef.current!.twitter_username.value = response.twitter_username; - formRef.current!.company.value = response.company; - formRef.current!.location.value = response.location; - formRef.current!.github_sponsors_url.value = response.github_sponsors_url; - formRef.current!.linkedin_url.value = response.linkedin_url; - formRef.current!.discord_url.value = response.discord_url; - } + const response = session; + + if (response && !userInfo) { + setUserInfo(response); + formRef.current!.nameInput.value = response.name; + setEmail(response.email); + setDisplayLocalTime(response.display_local_time); + formRef.current!.bio.value = response.bio; + formRef.current!.url.value = response.url; + formRef.current!.twitter_username.value = response.twitter_username; + formRef.current!.company.value = response.company; + formRef.current!.location.value = response.location; + formRef.current!.github_sponsors_url.value = response.github_sponsors_url; + formRef.current!.linkedin_url.value = response.linkedin_url; + formRef.current!.discord_url.value = response.discord_url; } - fetchAuthSession(); }, [user]); useEffect(() => { @@ -251,7 +248,7 @@ const UserSettingsPage = ({ user }: userSettingsPageProps) => { name="linkedin_url" /> { const user = useUser(); const router = useRouter(); + const { session: isValid } = useSession(true); async function checkSession() { if (router.asPath?.includes("login")) return; - const isValid = await authSession(); - if (!isValid) { router.replace("/javascript/dashboard/filter/recent"); } diff --git a/lib/hooks/authSession.ts b/lib/hooks/authSession.ts deleted file mode 100644 index 9ce13749a4..0000000000 --- a/lib/hooks/authSession.ts +++ /dev/null @@ -1,24 +0,0 @@ -import { supabase } from "lib/utils/supabase"; - -const baseUrl = process.env.NEXT_PUBLIC_API_URL; -interface UserResponse extends DbUser {} -const authSession = async () => { - const sessionResponse = await supabase.auth.getSession(); - const sessionToken = sessionResponse?.data.session?.access_token; - // const { data, error } = useSWR("auth/session", publicApiFetcher as Fetcher); - const response = await fetch(`${baseUrl}/auth/session`, { - headers: { - Accept: "application/json", - "Content-Type": "application/json", - Authorization: `Bearer ${sessionToken}`, - }, - }); - - if (response.status === 200) { - return response.json(); - } else { - return false; - } -}; - -export { authSession }; diff --git a/lib/hooks/useSession.ts b/lib/hooks/useSession.ts index c072e18b1f..30b9ef046a 100644 --- a/lib/hooks/useSession.ts +++ b/lib/hooks/useSession.ts @@ -1,7 +1,5 @@ -import { useEffect } from "react"; - +import { useEffect, useState } from "react"; import useStore from "lib/store"; - import useSupabaseAuth from "./useSupabaseAuth"; const useSession = (getSession = false) => { @@ -10,37 +8,52 @@ const useSession = (getSession = false) => { const hasReports = useStore((state) => state.hasReports); const onboarded = useStore((state) => state.onboarded); const waitlisted = useStore((state) => state.waitlisted); + const [session, setSession] = useState(false); - async function loadSession() { - const resp = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/auth/session`, { + const loadSession = async () => { + const response = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/auth/session`, { method: "GET", headers: { + Accept: "application/json", + "Content-Type": "application/json", Authorization: `Bearer ${sessionToken}`, }, }); - if (resp.ok) { - const data = await resp.json(); - - store.setSession({ - onboarded: data.is_onboarded, - waitlisted: data.is_waitlisted, - insightRepoLimit: data.insights_role >= 50 ? 50 : 10, - }); - - store.setHasReports(data.insights_role >= 50); + if (response.status === 200) { + const data = await response.json(); + return data; } else { - // show an alert + return false; } - } + }; + + const setStoreData = (isOnboarded: boolean, isWaitlisted: boolean, insightsRole: number) => { + store.setSession({ + onboarded: isOnboarded, + waitlisted: isWaitlisted, + insightRepoLimit: insightsRole >= 50 ? 50 : 10, + }); + + store.setHasReports(insightsRole >= 50); + }; useEffect(() => { - if (sessionToken && getSession) { - loadSession(); - } + (async () => { + if (sessionToken && getSession) { + const data = await loadSession(); + setSession(data); + setStoreData(data.is_onboarded, data.is_waitlisted, data.insights_role); + } + })(); }, [sessionToken]); - return { onboarded, waitlisted, hasReports }; + return { + onboarded, + waitlisted, + hasReports, + session, + }; }; export default useSession; diff --git a/next-types.d.ts b/next-types.d.ts index 8a06fa1823..2dc9c5c23e 100644 --- a/next-types.d.ts +++ b/next-types.d.ts @@ -155,6 +155,7 @@ interface DbUser { readonly is_waitlisted: boolean; readonly role: number; readonly bio: string; + readonly url: string; readonly twitter_username: string; readonly company: string; readonly location: string;