Skip to content

Commit

Permalink
refactor: merge authSession function into useSession hook (#1391)
Browse files Browse the repository at this point in the history
Co-authored-by: Brandon Roberts <robertsbt@gmail.com>
  • Loading branch information
babblebey and brandonroberts committed Jul 25, 2023
1 parent cbabaf2 commit d6c230d
Show file tree
Hide file tree
Showing 6 changed files with 57 additions and 73 deletions.
8 changes: 3 additions & 5 deletions components/molecules/AuthSection/auth-section.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand All @@ -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<DbUserNotification[]>([]);
const [loading, setLoading] = useState(false);
const [userInfo, setUserInfo] = useState<DbUser | undefined>(undefined);
Expand Down Expand Up @@ -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);
}
};

Expand Down
37 changes: 17 additions & 20 deletions components/organisms/UserSettingsPage/user-settings-page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand All @@ -37,7 +36,7 @@ const UserSettingsPage = ({ user }: userSettingsPageProps) => {
revalidateOnFocus: false,
});

const { hasReports } = useSession();
const { hasReports, session } = useSession(true);

const { toast } = useToast();

Expand All @@ -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(() => {
Expand Down Expand Up @@ -251,7 +248,7 @@ const UserSettingsPage = ({ user }: userSettingsPageProps) => {
name="linkedin_url"
/>
<TextInput
className="font-medium bg-light-slate-4 text-light-slate-11"
className="bg-light-slate-4 text-light-slate-11 font-medium"
placeholder="https://discordapp.com/users/832877193112762362"
label="Discord URL"
onChange={handleValidateDiscordUrl}
Expand Down
5 changes: 2 additions & 3 deletions layouts/private-wrapper.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { useUser } from "@supabase/auth-helpers-react";
import { useRouter } from "next/router";
import React, { useEffect } from "react";
import { authSession } from "lib/hooks/authSession";
import useSession from "lib/hooks/useSession";

interface PrivateWrapperProps {
isPrivateRoute?: boolean;
Expand All @@ -11,12 +11,11 @@ interface PrivateWrapperProps {
const PrivateWrapper = ({ isPrivateRoute = false, children }: PrivateWrapperProps) => {
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");
}
Expand Down
24 changes: 0 additions & 24 deletions lib/hooks/authSession.ts

This file was deleted.

55 changes: 34 additions & 21 deletions lib/hooks/useSession.ts
Original file line number Diff line number Diff line change
@@ -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) => {
Expand All @@ -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 | DbUser>(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;
1 change: 1 addition & 0 deletions next-types.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down

0 comments on commit d6c230d

Please sign in to comment.