Skip to content

Commit

Permalink
feat(auth): adjust authState
Browse files Browse the repository at this point in the history
  • Loading branch information
ridhlab committed Dec 27, 2023
1 parent 51cd38a commit 996f649
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 19 deletions.
21 changes: 4 additions & 17 deletions src/contexts/AuthContext.tsx
Original file line number Diff line number Diff line change
@@ -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";
Expand Down Expand Up @@ -31,10 +30,7 @@ interface IProps {
}

export const AuthContextProvider: React.FC<IProps> = ({ children }) => {
const { isLoading, setIsLoading } = useLoading();
const [user, setUser] = React.useState<IUser>(null);
const [error, setError] = React.useState(null);

const queryUser = useGetUser();

const afterLoginRegister = (user: IUser) => {
Expand All @@ -45,20 +41,11 @@ export const AuthContextProvider: React.FC<IProps> = ({ 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,
Expand Down
9 changes: 7 additions & 2 deletions src/routes/PrivateRoute.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,13 @@ interface IProps {

const PrivateRoute = ({ children }: IProps) => {
const { isLoading, isAuthenticate } = useAuthContext();
if (isLoading) return <LoaderFullscreen />;
return !isAuthenticate ? <Navigate to={Routes.Login} /> : children;
return !isAuthenticate ? (
<Navigate to={Routes.Login} />
) : isLoading ? (
<LoaderFullscreen />
) : (
children
);
};

export default PrivateRoute;

0 comments on commit 996f649

Please sign in to comment.