Skip to content

Commit

Permalink
feat: 마이페이지 리팩토링 (#222)
Browse files Browse the repository at this point in the history
* refactor: 하단에 hidden component를 추가하여 relative하게 중앙 정렬

* feat: 마이페이지에 계정 탈퇴 메뉴 추가

* refactor: useQuery로 api 호출 방식 변경

* feat: privateRoute hooks 구현

* feat: Nav Bar 로그아웃 기능 추가

* refactor: privateRoute에서 로그아웃 후 login 페이지로 이동하는 방식으로 변경

* refactor: PrivateRoute outlet 중첩 라우팅으로 수정

* fix: 기존에 userState 사용하는 로직 삭제, resetUserInfo 적용

* refactor: useQuery에서 useMutation으로 변경, useCurrentPasswordForm 내부로 위치 변경

* fix: resetUserInfo 중복 선언 제거

* fix: PrivateRoute 적용 페이지 추가
  • Loading branch information
jonique98 authored Jun 26, 2024
1 parent a69780d commit a19cbb8
Show file tree
Hide file tree
Showing 9 changed files with 84 additions and 55 deletions.
29 changes: 7 additions & 22 deletions src/home/apis/getUserPasswordMatch.ts
Original file line number Diff line number Diff line change
@@ -1,26 +1,11 @@
import { AxiosError } from 'axios';

import { authClient } from '@/apis';
import { AuthErrorData } from '@/home/types/Auth.type';
import { GetPasswordResponse } from '@/home/types/password.type';
import { SessionTokenType } from '@/home/types/password.type';
import { api } from '@/service/TokenService';

interface getPasswordProps {
password: string;
}

export const getUserPasswordMatch = async (
props: getPasswordProps
): Promise<GetPasswordResponse> => {
const { password } = props;

try {
const res = await authClient.get('/auth/verification/password', {
params: { password },
headers: api.headers,
});
return { data: res.data };
} catch (error: unknown) {
return { error: error as AxiosError<AuthErrorData> };
}
export const getUserPasswordMatch = async (password: string): Promise<SessionTokenType> => {
const res = await authClient.get('/auth/verification/password', {
params: { password },
headers: api.headers,
});
return res.data;
};
Original file line number Diff line number Diff line change
Expand Up @@ -2,25 +2,28 @@ import { Link } from 'react-router-dom';
import styled from 'styled-components';

export const StyledChangePasswordFrame = styled.div`
flex: 1;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
gap: 24px;
`;

margin-bottom: 101px;
export const StyledLink = styled(Link)``;

export const StyledHiddenDiv = styled.div`
transform: rotate(180deg);
visibility: hidden;
`;

export const StyledLink = styled(Link)`
export const StyledLogo = styled.img`
width: 180px;
height: 29px;
`;

export const StyledLogo = styled.img`
width: 100%;
height: 100%;
export const StyledHiddenLogo = styled.img`
width: 180px;
height: 29px;
`;

export const StyledContainer = styled.div`
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ import {
StyledContainer,
StyledLink,
StyledLogo,
StyledHiddenLogo,
StyledHiddenDiv,
} from './ChangePasswordFrame.style';

interface ChangePasswordFrameProps {
Expand All @@ -18,6 +20,9 @@ export const ChangePasswordFrame = ({ children }: ChangePasswordFrameProps) => {
<StyledLogo src={Logo} alt="soomsil" />
</StyledLink>
<StyledContainer>{children}</StyledContainer>
<StyledHiddenDiv>
<StyledHiddenLogo />
</StyledHiddenDiv>
</StyledChangePasswordFrame>
);
};
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ interface CurrentPasswordFormProps {
}

export const CurrentPasswordForm = (props: CurrentPasswordFormProps) => {
const { currentPassword, isError, handlePasswordChange, checkCurrentPassword } =
const { currentPassword, isPasswordError, handlePasswordChange, checkCurrentPassword } =
useCurrentPasswordForm(props);

return (
Expand All @@ -30,8 +30,8 @@ export const CurrentPasswordForm = (props: CurrentPasswordFormProps) => {
placeholder="비밀번호를 입력해주세요."
value={currentPassword}
onChange={(e) => handlePasswordChange(e.target.value)}
isNegative={isError}
helperLabel={isError ? '비밀번호가 일치하지 않습니다.' : ''}
isNegative={isPasswordError}
helperLabel={isPasswordError ? '비밀번호가 일치하지 않습니다.' : ''}
/>
</StyledInputContainer>
<StyledButtonContainer>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { useState } from 'react';

import { useMutation } from '@tanstack/react-query';
import { useNavigate } from 'react-router-dom';
import { useRecoilValue } from 'recoil';

Expand All @@ -18,37 +19,40 @@ export const useCurrentPasswordForm = ({
setSessionToken,
setPreviousPassword,
}: CurrentPasswordFormProps) => {
const [currentPassword, setCurrentPassword] = useState('');
const [isError, setIsError] = useState(false);
const [currentPassword, setCurrentPassword] = useState<string>('');
const [isPasswordError, setIsPasswordError] = useState<boolean>(false);
const isLoggedIn = useRecoilValue(LogInState);
const navigate = useNavigate();

const checkCurrentPassword = async () => {
const passwordMatchMutation = useMutation({
mutationFn: getUserPasswordMatch,
onSuccess: (data) => {
setSessionToken(data);
setPreviousPassword(currentPassword);
onConfirm();
},
onError: () => {
setIsPasswordError(true);
},
});

const checkCurrentPassword = () => {
if (!isLoggedIn) {
navigate('/Login');
return;
}

const { error, data } = await getUserPasswordMatch({
password: currentPassword,
});

if (data) {
setIsError(false);
setSessionToken(data as SessionTokenType);
setPreviousPassword(currentPassword);
onConfirm();
} else if (error) setIsError(true);
passwordMatchMutation.mutate(currentPassword);
};

const handlePasswordChange = (password: string) => {
if (isError) setIsError(false);
if (isPasswordError) setIsPasswordError(false);
setCurrentPassword(password);
};

return {
currentPassword,
isError,
isPasswordError,
handlePasswordChange,
checkCurrentPassword,
};
Expand Down
2 changes: 1 addition & 1 deletion src/home/components/Dialog/LogoutModal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,8 @@ interface LogoutModalProps {
}

export const LogoutModal = ({ open, onOpenChange }: LogoutModalProps) => {
const navigate = useNavigate();
const resetUserInfo = useResetUserInfo();
const navigate = useNavigate();

const handleLogout = () => {
resetUserInfo();
Expand Down
1 change: 1 addition & 0 deletions src/home/components/MyMenuList/MyMenuList.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ export const MyMenuList = () => {
<StyledListItem onClick={() => navigate('/changePassword')}>
비밀번호 변경
</StyledListItem>
<StyledListItem onClick={() => navigate('/withdraw')}>계정탈퇴</StyledListItem>
<StyledListItem onClick={() => setIsOpenModal(true)}>로그아웃</StyledListItem>
</StyledMenuContainer>
<StyledMenuContainer>
Expand Down
24 changes: 24 additions & 0 deletions src/hooks/usePrivateRoute.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import { Navigate, Outlet } from 'react-router-dom';
import { useRecoilValue } from 'recoil';

import { LogInState } from '@/home/recoil/LogInState';
import { api } from '@/service/TokenService';

import { useResetUserInfo } from './useResetUserInfo';

export const usePrivateRoute = () => {
const isLoggedIn = useRecoilValue(LogInState);
const accessToken = api.getAccessToken();

const resetUserInfo = useResetUserInfo();

const PrivateRoute = (): React.ReactNode => {
if (!isLoggedIn || !accessToken) {
resetUserInfo();
return <Navigate to="/login" />;
}
return <Outlet />;
};

return { PrivateRoute };
};
21 changes: 14 additions & 7 deletions src/router.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { Navigate, Route, Routes } from 'react-router-dom';

import { Fallback } from '@/components/Fallback/Fallback';
import { ProgressBar } from '@/components/ProgressBar/ProgressBar';
import { usePrivateRoute } from '@/hooks/usePrivateRoute';

const Search = lazy(() =>
import('./search/pages/Search/Search').then(({ Search }) => ({
Expand Down Expand Up @@ -112,6 +113,8 @@ export const Router = () => {
};
}, []);

const { PrivateRoute } = usePrivateRoute();

return (
<ErrorBoundary fallbackRender={(fallbackProps) => <Fallback {...fallbackProps} />}>
<Suspense
Expand All @@ -127,17 +130,21 @@ export const Router = () => {
<Routes>
<Route path="/" element={<Home />}></Route>
<Route path="/login" element={<Login />}></Route>
<Route path="/signup" element={<Signup />}></Route>
<Route path="/resetpassword" element={<ResetPassword />} />
<Route path="/changePassword" element={<ChangePassword />} />
<Route path="/mypage" element={<Mypage />}></Route>
<Route path="/withdraw" element={<Withdraw />}></Route>
<Route path="/Signup" element={<Signup />}></Route>
<Route element={<PrivateRoute />}>
<Route path="/Mypage" element={<Mypage />}></Route>
<Route path="/changePassword" element={<ChangePassword />}></Route>
<Route path="/withdraw" element={<Withdraw />}></Route>
<Route path="/resetPassword" element={<ResetPassword />}></Route>
</Route>
<Route path="/drawer" element={<DrawerLayout />}>
<Route index element={<Navigate to="rankings" replace />}></Route>
<Route path="services/:serviceId" element={<ServiceDetail />} />
<Route path="rankings" element={<Ranking />} />
<Route path="register" element={<Register />} />
<Route path="myDrawers" element={<MyDrawer />} />
<Route element={<PrivateRoute />}>
<Route path="register" element={<Register />} />
<Route path="myDrawers" element={<MyDrawer />} />
</Route>
<Route path="/drawer/newRelease" element={<NewRelease />} />
<Route path="/drawer/starRanking" element={<StarRanking />} />
<Route path=":providerId" element={<Provider />} />
Expand Down

0 comments on commit a19cbb8

Please sign in to comment.