From e1682d72e2e2ef0616b1d14cdee42918efaacae7 Mon Sep 17 00:00:00 2001 From: Kevin Tun Date: Thu, 30 May 2024 12:52:12 -0500 Subject: [PATCH] feat(addpage.tsx): refactor authentication logic to use @logto/react library for improved user authentication handling The code now uses the useLogto hook from the @logto/react library to handle user authentication logic. This change improves the codebase by centralizing authentication logic and making it more maintainable. The useEffect hook is used to fetch user data asynchronously when the component mounts, ensuring that the user information is up to date. --- .../src/pages/information/[name]/addpage.tsx | 22 ++++++++++++++----- 1 file changed, 16 insertions(+), 6 deletions(-) diff --git a/apps/stock-center/src/pages/information/[name]/addpage.tsx b/apps/stock-center/src/pages/information/[name]/addpage.tsx index 034406d8c..40b6ca4e5 100644 --- a/apps/stock-center/src/pages/information/[name]/addpage.tsx +++ b/apps/stock-center/src/pages/information/[name]/addpage.tsx @@ -1,3 +1,5 @@ +import { useState, useEffect } from "react" +import { useLogto, UserInfoResponse } from "@logto/react" import { Navigate } from "react-router-dom" import { useContentBySlugQuery } from "dicty-graphql-schema" import { match, P } from "ts-pattern" @@ -6,7 +8,7 @@ import { FullPageLoadingDisplay, contentPageErrorMatcher, } from "@dictybase/ui-common" -import { ACCESS, useTokenAndUser } from "@dictybase/auth" +import { ACCESS } from "@dictybase/auth" import { NAMESPACE } from "../../../namespace" import { useSlug } from "../../../hooks/useSlug" import { useContentPath } from "../../../hooks/useContentPath" @@ -19,11 +21,19 @@ const AddPage = () => { errorPolicy: "all", fetchPolicy: "network-only", }) - const { token, user } = useTokenAndUser( - import.meta.env.VITE_APP_LOGTO_API_SECOND_RESOURCE, - ) + const { fetchUserInfo, getAccessToken, isAuthenticated } = useLogto() + const [user, setUser] = useState() + useEffect(() => { + const getUserData = async () => { + if (!isAuthenticated) return + setUser(await fetchUserInfo()) + } + + getUserData() + }, [fetchUserInfo, getAccessToken, isAuthenticated]) + return match({ - token, + getAccessToken, user, ...result, }) @@ -34,7 +44,7 @@ const AddPage = () => { .with({ error: P.select(P.not(undefined)) }, (error) => contentPageErrorMatcher(error, () => (