Skip to content

Commit

Permalink
refactor: useCoopMe 훅 생성
Browse files Browse the repository at this point in the history
  • Loading branch information
junghaesung79 committed Jun 26, 2024
1 parent 17871ff commit e23d11a
Show file tree
Hide file tree
Showing 4 changed files with 62 additions and 46 deletions.
50 changes: 24 additions & 26 deletions src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,41 +1,39 @@
import { Suspense, useEffect } from 'react';

import { Route, Routes, useNavigate } from 'react-router-dom';
import {
Route, Routes, Navigate, Outlet,
} from 'react-router-dom';

import AuthLayout from 'layout/AuthLayout';
import DefaultLayout from 'layout/DefaultLayout';
import Coop from 'pages/Coop';
import Login from 'pages/Login';
import useUserStore from 'store/useUserStore';
import { useCoopMe } from 'query/auth';

function App() {
const { isAuthenticated, initializeAuth } = useUserStore();
const navigate = useNavigate();
function ProtectedRoute() {
const { user, isLoading } = useCoopMe();

useEffect(() => {
const checkAuth = async () => {
await initializeAuth();
};
checkAuth().then(() => {
if (isAuthenticated) {
navigate('/');
} else {
navigate('/login');
}
});
}, [isAuthenticated, initializeAuth, navigate]);
if (isLoading) {
return <div>Loading...</div>;
}

if (!user) {
return <Navigate to="/login" />;
}

return <Outlet />;
}

function App() {
return (
<Suspense fallback={<div />}>
<Routes>
<Routes>
<Route element={<ProtectedRoute />}>
<Route element={<DefaultLayout />}>
<Route path="/" element={<Coop />} />
</Route>
<Route element={<AuthLayout />}>
<Route path="/login" element={<Login />} />
</Route>
</Routes>
</Suspense>
</Route>
<Route element={<AuthLayout />}>
<Route path="/login" element={<Login />} />
</Route>
</Routes>
);
}

Expand Down
12 changes: 9 additions & 3 deletions src/index.tsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,14 @@
import { Suspense } from 'react';

import { BrowserRouter } from 'react-router-dom';

import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import ReactDOM from 'react-dom/client';
import { ZodError } from 'zod';

import App from './App';
import ErrorBoundary from './layout/ErrorBoundary';

import './index.scss';

const queryClient = new QueryClient({
Expand All @@ -15,10 +19,10 @@ const queryClient = new QueryClient({
refetchOnReconnect: true,
retry: 4,
staleTime: 1000 * 60 * 5,
throwOnError: true,
throwOnError: (err) => err instanceof ZodError,
},
mutations: {
throwOnError: true,
throwOnError: (err) => err instanceof ZodError,
},
},
});
Expand All @@ -27,7 +31,9 @@ ReactDOM.createRoot(document.getElementById('root') as HTMLElement).render(
<ErrorBoundary message="에러가 발생했습니다.">
<QueryClientProvider client={queryClient}>
<BrowserRouter>
<App />
<Suspense fallback={<div />}>
<App />
</Suspense>
</BrowserRouter>
</QueryClientProvider>
</ErrorBoundary>,
Expand Down
5 changes: 2 additions & 3 deletions src/layout/Header/MobilePanel/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,8 @@ import MobileLogoIcon from 'assets/svg/common/mobile-koin-logo.svg?react';
import useMediaQuery from 'hooks/useMediaQuery';
import useMobileSidebar from 'layout/Header/hooks/useMobileSidebar';
import { CATEGORY_COOP, HeaderCategory } from 'models/headerCategory';
import { useLogout } from 'query/auth';
import { useCoopMe, useLogout } from 'query/auth';
import usePrevPathStore from 'store/usePrevPathStore';
import useUserStore from 'store/useUserStore';
import cn from 'utils/className';

import { createPortal } from 'react-dom';
Expand Down Expand Up @@ -54,7 +53,7 @@ export default function MobilePanel() {
const navigate = useNavigate();
const { pathname } = useLocation();
const { isMobile } = useMediaQuery();
const { user } = useUserStore();
const { user } = useCoopMe();

const { setPrevPath } = usePrevPathStore();
const { logout } = useLogout();
Expand Down
41 changes: 27 additions & 14 deletions src/query/auth.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,16 @@
import { useNavigate } from 'react-router-dom';

import { postLogin, postLogout } from 'api/auth';
import { getCoopMe, postLogin, postLogout } from 'api/auth';
import { LoginForm, LoginResponse } from 'models/auth';
import { useErrorMessageStore } from 'store/useErrorMessageStore';
import useUserStore from 'store/useUserStore';

import { isKoinError, sendClientError } from '@bcsdlab/koin';
import { useMutation } from '@tanstack/react-query';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';

export const useLogin = () => {
const { setLoginError, setLoginErrorStatus } = useErrorMessageStore();
const navigate = useNavigate();
const { initializeAuth } = useUserStore();
const queryClient = useQueryClient();

const {
mutate, error, isError, isSuccess,
Expand All @@ -25,14 +24,14 @@ export const useLogin = () => {
if (form.isAutoLogin) {
localStorage.setItem('refresh_token', data.refresh_token);
}
await initializeAuth();

await queryClient.invalidateQueries({ queryKey: ['user'] });
navigate('/');
},
onError: (err) => {
if (isKoinError(err)) {
setLoginError(err.message || '로그인을 실패했습니다.');
sessionStorage.removeItem('access_token');
sessionStorage.removeItem('user_storage');
localStorage.removeItem('refresh_token');

switch (err.status) {
Expand Down Expand Up @@ -63,19 +62,14 @@ export const useLogin = () => {

export const useLogout = () => {
const { setLogoutError, setLogoutErrorCode } = useErrorMessageStore();
const queryClient = useQueryClient();

const { mutate, error, isError } = useMutation({
mutationFn: async () => {
const response = await postLogout();
if (response) {
return true;
}
throw new Error('로그아웃 실패');
},
mutationFn: async () => postLogout(),
onSuccess: () => {
sessionStorage.removeItem('access_token');
sessionStorage.removeItem('user_storage');
localStorage.removeItem('refresh_token');
queryClient.invalidateQueries({ queryKey: ['user'] });
},
onError: (err) => {
if (isKoinError(err)) {
Expand All @@ -89,3 +83,22 @@ export const useLogout = () => {

return { logout: mutate, error, isError };
};

export const useCoopMe = () => {
const token = sessionStorage.getItem('access_token');

const {
data, error, isError, isLoading,
} = useQuery({
queryKey: ['user'],
queryFn: async () => {
const response = await getCoopMe();
return response;
},
enabled: !!token,
});

return {
user: data, error, isError, isLoading,
};
};

0 comments on commit e23d11a

Please sign in to comment.