Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

코드 리팩토링 #167

Merged
merged 7 commits into from
Nov 7, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions src/commons/Input.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,13 @@ const Input = ({
onChange,
autocomplete,
defaultValue,
dataInputType,
}: InputGroupProps) => {
return (
<input
className="border-2 rounded-md border-gray-300 p-2"
id={id}
data-input-type={dataInputType}
name={name}
type={type}
placeholder={placeholder}
Expand Down
3 changes: 3 additions & 0 deletions src/commons/InputGroup.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ export interface InputGroupProps
type: string;
onChange?: (e: React.ChangeEvent<HTMLInputElement>) => void;
autocomplete?: string;
dataInputType?: string;
}

const InputGroup = ({
Expand All @@ -18,6 +19,7 @@ const InputGroup = ({
onChange,
autocomplete,
defaultValue,
dataInputType,
}: InputGroupProps) => {
return (
<Container className={'flex flex-col gap-1'}>
Expand All @@ -26,6 +28,7 @@ const InputGroup = ({
</label>
<Input
id={id}
dataInputType={dataInputType}
name={name}
type={type}
placeholder={placeholder}
Expand Down
7 changes: 1 addition & 6 deletions src/commons/UserDropdownBox.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { useNavigate } from 'react-router-dom';
import { useState } from 'react';
import { getCookie, removeCookie, setCookie } from './cookie/cookie';
import { getCookie, removeToken, setCookie } from './cookie/cookie';

// 로그인 되었을 때 상태를 보여주는 SelectBox 제작
const UserDropdownBox = () => {
Expand All @@ -15,11 +15,6 @@ const UserDropdownBox = () => {
setIsDropdownOpen(!isDropdownOpen);
};

const removeToken = () => {
removeCookie('loginToken');
removeCookie('userAccountInfo');
};

const handleOptionClick = (option: string) => {
switch (option) {
case 'My 정보 변경':
Expand Down
7 changes: 1 addition & 6 deletions src/commons/UserToggleBox.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import React, { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { getCookie, removeCookie, setCookie } from './cookie/cookie';
import { getCookie, removeToken, setCookie } from './cookie/cookie';

const UserToggleBox = () => {
const token = getCookie('loginToken');
Expand All @@ -13,11 +13,6 @@ const UserToggleBox = () => {
setTabVisible(!isTabVisible);
};

const removeToken = () => {
removeCookie('loginToken');
removeCookie('userAccountInfo');
};

const handleOptionClick = (option: string) => {
switch (option) {
case 'My 정보 변경':
Expand Down
16 changes: 15 additions & 1 deletion src/commons/cookie/cookie.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,16 @@ import { Cookies } from 'react-cookie';

const cookies = new Cookies();

export const setCookie = (name: string, value: string, option?: any) => {
type CookieSetOptions = {
expires?: Date;
maxAge?: number;
};

export const setCookie = (
name: string,
value: string,
option?: CookieSetOptions,
) => {
return cookies.set(name, value, { ...option });
};

Expand All @@ -14,3 +23,8 @@ export const getCookie = (name: string) => {
export const removeCookie = (name: string) => {
return cookies.remove(name);
};

export const removeToken = () => {
removeCookie('loginToken');
removeCookie('userAccountInfo');
};
2 changes: 1 addition & 1 deletion src/commons/modals/LoginGuideModal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ const LoginGuideModal = () => {
<button
className="bg-brand-color text-white rounded-md px-4 py-1 transition duration-300 hover:bg-white hover:text-brand-color"
onClick={() => {
setCookie('userAccountInfo', 'Not Login');
setCookie('userAccountInfo', 'Not Login', { maxAge: 60000 * 30 }); // 30분
setIsLogined(true);
}}
>
Expand Down
4 changes: 3 additions & 1 deletion src/layouts/ValidateCheckLayout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,10 @@ const ValidateCheckLayout: React.FC<LayoutProps> = ({ children }) => {
const loginToken = getCookie('loginToken');
const userAccount = getCookie('userAccountInfo');

// userAccount에 대한 정책 수정이 필요
// Layout 먹이는 방식 수정
useEffect(() => {
if (!loginToken && !userAccount) {
if (!loginToken && userAccount) {
// loginToken이 없으면 모달 열기
setIsLogined(false);
}
Expand Down
2 changes: 1 addition & 1 deletion src/pages/editProfile/EditAddressInputGroup.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import VAddressInputGroup from 'pages/signUp/VAddressInputGroup';
import VAddressInputGroup from 'pages/signUp/components/VAddressInputGroup';
import { useRecoilState } from 'recoil';
import { shelterSignupState } from 'recoil/shelterState';

Expand Down
72 changes: 37 additions & 35 deletions src/pages/login/LoginInputForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { useRecoilState } from 'recoil';
import { useNavigate } from 'react-router-dom';
import { ShelterLoginType, shelterLoginState } from 'recoil/shelterState';
import * as Yup from 'yup';
import { useMutation } from '@tanstack/react-query';
import VLoginInputForm from './VLoginInputForm';
import { setCookie } from '../../commons/cookie/cookie';

Expand All @@ -20,9 +21,8 @@ const LoginInputForm = () => {
password: Yup.string().required('비밀번호를 입력해주세요.'),
});

const userfetch = () => {
let token: string;
fetch(`${process.env.REACT_APP_URI}/account/login`, {
const userFetch = async () => {
const res = await fetch(`${process.env.REACT_APP_URI}/account/login`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Expand All @@ -32,38 +32,19 @@ const LoginInputForm = () => {
email: userInfo.email,
password: userInfo.password,
}),
}).then(async (res) => {
const jwtToken = res.headers.get('Authorization');
if (jwtToken) {
// eslint-disable-next-line prefer-destructuring
token = jwtToken.split(' ')[1];
} else {
console.log('로그인 실패로 token이 Null');
}
const data = await res.json();
if (data.success && token) {
const { accountInfo, tokenExpirationDateTime } = data.response;
const { id, role } = accountInfo;
const tokenExpirationDate = new Date(tokenExpirationDateTime);
const timeDifferenceseconds = Math.floor(
(Number(tokenExpirationDate) - Number(currentDate)) / 1000,
);

setCookie('accountInfo', `${role} ${id}`, {
expires: tokenExpirationDate,
maxAge: timeDifferenceseconds,
});
setCookie('loginToken', token, {
expires: tokenExpirationDate,
maxAge: timeDifferenceseconds,
});
navigate('/');
} else {
// 형식은 맞지만 입력된 값이 가입되지 않은 계정일 때
alert(data.error.message);
}
setIsLoading(false);
});

if (!res.ok) {
// error 발생 시 처리는 status 값에 따라 하는 것으로 변경 필요
const errorData = await res.json();
console.error('userFetchError: ', errorData);
}

const response = await res.json();
const jwtToken = res.headers.get('Authorization');
const token = jwtToken ? jwtToken.split(' ')[1] : '';

return { response, token };
};

const validateCheck = () => {
Expand All @@ -83,11 +64,32 @@ const LoginInputForm = () => {
});
};

const mutation = useMutation(userFetch, {
onSuccess: (data) => {
const { accountInfo, tokenExpirationDateTime } = data.response.response;
const { id, role } = accountInfo;
const tokenExpirationDate = new Date(tokenExpirationDateTime);
const timeDifferenceseconds = Math.floor(
(Number(tokenExpirationDate) - Number(currentDate)) / 1000,
);

setCookie('accountInfo', `${role} ${id}`, {
expires: tokenExpirationDate,
maxAge: timeDifferenceseconds,
});
setCookie('loginToken', data.token, {
expires: tokenExpirationDate,
maxAge: timeDifferenceseconds,
});
navigate('/');
},
});

const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
setIsLoading(true);
validateCheck();
userfetch();
mutation.mutate();
};

const handleChange = (event: React.ChangeEvent<HTMLInputElement>) => {
Expand Down
136 changes: 0 additions & 136 deletions src/pages/map/TestMap.tsx

This file was deleted.

1 change: 1 addition & 0 deletions src/pages/map/useMap.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import displayMarker from './displayMarker';
function useMap<T>(
containerRef: RefObject<T extends HTMLElement ? T : HTMLElement>,
) {
const { kakao } = window;
const [map, setMap] = useState<any>();
const [searchedPlace, setSearchedPlace] = useState<any>([]);
const boundRef = useRef<any>();
Expand Down
Loading