From 996f64919073ef100b9045335520c2d5e631b61e Mon Sep 17 00:00:00 2001 From: ridhlab Date: Wed, 27 Dec 2023 19:47:27 +0700 Subject: [PATCH] feat(auth): adjust authState --- src/contexts/AuthContext.tsx | 21 ++++----------------- src/routes/PrivateRoute.tsx | 9 +++++++-- 2 files changed, 11 insertions(+), 19 deletions(-) diff --git a/src/contexts/AuthContext.tsx b/src/contexts/AuthContext.tsx index c40d89a..4132b7c 100644 --- a/src/contexts/AuthContext.tsx +++ b/src/contexts/AuthContext.tsx @@ -1,6 +1,5 @@ import { AUTH_TOKEN_NAME } from "@/constants/auth"; import { getCookie } from "@/helpers/cookie"; -import { useLoading } from "@/hooks/useLoading"; import { IUser } from "@/interfaces/entities/Users"; import { IBaseResponse } from "@/interfaces/responses/base"; import { useGetUser } from "@/services/query/Auth"; @@ -31,10 +30,7 @@ interface IProps { } export const AuthContextProvider: React.FC = ({ children }) => { - const { isLoading, setIsLoading } = useLoading(); const [user, setUser] = React.useState(null); - const [error, setError] = React.useState(null); - const queryUser = useGetUser(); const afterLoginRegister = (user: IUser) => { @@ -45,20 +41,11 @@ export const AuthContextProvider: React.FC = ({ children }) => { setUser(null); }; - React.useEffect(() => { - if (queryUser) { - setIsLoading(queryUser.isLoading); - setError(queryUser.error); - setUser(queryUser.data); - } - // eslint-disable-next-line react-hooks/exhaustive-deps - }, [queryUser]); - const authState: IAuthContextData = { - isLoading: isLoading, - user: user, - error: error, - isError: !!error, + isLoading: queryUser.isLoading, + user: user ?? queryUser.data, + error: queryUser.error, + isError: !!queryUser.error, isAuthenticate: !!getCookie(AUTH_TOKEN_NAME), afterLoginRegister, afterLogout, diff --git a/src/routes/PrivateRoute.tsx b/src/routes/PrivateRoute.tsx index 74adc6b..fc25263 100644 --- a/src/routes/PrivateRoute.tsx +++ b/src/routes/PrivateRoute.tsx @@ -10,8 +10,13 @@ interface IProps { const PrivateRoute = ({ children }: IProps) => { const { isLoading, isAuthenticate } = useAuthContext(); - if (isLoading) return ; - return !isAuthenticate ? : children; + return !isAuthenticate ? ( + + ) : isLoading ? ( + + ) : ( + children + ); }; export default PrivateRoute;