Skip to content

Commit

Permalink
Merge pull request #142 from UMC-FITple/feat/#141
Browse files Browse the repository at this point in the history
Feat/#141 옷장 삭제 구현하기
  • Loading branch information
kangsuyeong authored Sep 23, 2024
2 parents 529b7da + e9eb817 commit 9345a5d
Show file tree
Hide file tree
Showing 9 changed files with 90 additions and 106 deletions.
89 changes: 31 additions & 58 deletions FITple-Frontend/data/MyPageApi.jsx
Original file line number Diff line number Diff line change
@@ -1,64 +1,37 @@
const API_BASE_URL = 'http://localhost:3000';
const API_BASE_URL = "http://localhost:3000";

export const submitUserInfo = async (data, imageFile) => {
const formData = new FormData();
formData.append('data', JSON.stringify(data));

if (imageFile) {
formData.append('image', imageFile);
const formData = new FormData();
formData.append("data", JSON.stringify(data));

if (imageFile) {
formData.append("image", imageFile);
}

try {
const response = await fetch(`${API_BASE_URL}/FITple/myprofile`, {
method: "POST",
headers: {
"Content-Type": "multipart/form-data",
},
body: formData,
credentials: "include",
});

if (!response.status === 200) {
if (response.status === 407) {
console.error("이미 존재하는 닉네임입니다.");
}
throw new Error(`Network response was not ok: ${response.status}`);
}

try {
const response = await fetch(`${API_BASE_URL}/FITple/myprofile`, {
method: 'POST',
headers: {
"Content-Type": "multipart/form-data",
},
body: formData,
credentials: 'include',
});

if (!response.status === 200) {
if (response.status === 407) {
console.error('이미 존재하는 닉네임입니다.');
}
throw new Error(`Network response was not ok: ${response.status}`);
}
const responseData = await response.json();
console.log("submit User Info!");
console.log(responseData);

const responseData = await response.json();
console.log('submit User Info!');
console.log(responseData);

return response;
} catch (error) {
console.error('Error:', error);
throw error;
}
return response;
} catch (error) {
console.error("Error:", error);
throw error;
}
};


// // 임시 토큰 발급 함수
// const fetchToken = async () => {
// try {
// const response = await fetch(`${API_BASE_URL}/temp-token`, {
// method: 'POST',
// headers: {
// 'Content-Type': 'application/json',
// },
// credentials: "include",
// body: JSON.stringify({
// // 필요한 경우 바디 데이터를 추가
// }),
// });

// if (!response.ok) {
// throw new Error('Failed to fetch token');
// }

// const data = await response.json();
// return data.token;
// } catch (error) {
// console.error('Error fetching token:', error);
// throw error;
// }
// };
2 changes: 1 addition & 1 deletion FITple-Frontend/data/ProfileApi.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ const localhost = "http://localhost:3000";
export const getInform = async () => {
try {
const url = new URL(`${localhost}/FITple/profile`);

const response = await fetch(url, {
method: "GET",
credentials: "include",
Expand All @@ -14,6 +13,7 @@ export const getInform = async () => {
}
return await response.json();
} catch (error) {
console.log(` ${response.status}`);
// console.error("유저정보를 불러올수없습니다.", error);
throw new Error("네트워크 오류가 발생했습니다. 잠시 후 다시 시도해주세요.");
}
Expand Down
9 changes: 0 additions & 9 deletions FITple-Frontend/data/store/store.jsx

This file was deleted.

48 changes: 32 additions & 16 deletions FITple-Frontend/data/store/userAuthStore.js
Original file line number Diff line number Diff line change
@@ -1,20 +1,36 @@
import { create } from "zustand";
import { persist } from "zustand/middleware";

const useAuthStore = create((set) => ({
token: localStorage.getItem("token") || null, // Rehydrate token from localStorage
authenticate: false,
setToken: (newToken) => {
localStorage.setItem("token", newToken);
set({ token: newToken });
},
setAuthenticate: (state) => {
set({ authenticate: state });
},
// const useAuthStore = create((set) => ({
// authenticate: false,
// setAuthenticate: (state) => {
// set({ authenticate: state });
// },

clearToken: () => {
localStorage.removeItem("token");
set({ token: null });
},
}));
// clearToken: () => {
// localStorage.removeItem("token");
// set({ token: null });
// },
// }));

export default useAuthStore;
// zustand persist을 이용해서 로그인 상태를 로컬 스토리지 같은 공간에 저장한다.
const userAuthStore = create(
persist(
(set, get) => ({
authenticate: false,
setAuthenticate: (state) => {
set({ authenticate: state });
},

clearToken: () => {
localStorage.removeItem("token");
set({ token: null });
},
}),
{
name: "useAuthStorage",
}
)
);

export default userAuthStore;
20 changes: 12 additions & 8 deletions FITple-Frontend/src/App.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -33,16 +33,16 @@ import ProfileEditPage from "./pages/ProfileEditPage/ProfileEditPage";
import ChangepwdPage from "./pages/ChangepwdPage/ChangepwdPage";
import NotFoundPage from "./pages/NotFoundPage/NotFoundPage";
import { useEffect } from "react";
import useAuthStore from "../data/store/userAuthStore";
import userAuthStore from "../data/store/userAuthStore";
import { getInform } from "../data/ProfileApi";
function App() {
const location = useLocation();
const { authenticate, setAuthenticate } = useAuthStore(); // 로그인 되었는지 안되어있는지 확인
const { authenticate, setAuthenticate } = userAuthStore(); // 로그인 되었는지 안되어있는지 확인

// 로그인되어있는지 확인
const PrivateRoute = React.useCallback(() => {
return authenticate ? <Outlet /> : <Navigate to="/login" />;
}, [authenticate]);
// authenticate가 변경될 때마다 로그 출력
useEffect(() => {
console.log("로그인 되어있는가?", authenticate);
}, [authenticate]); // authenticate가 변경될 때마다 실행

// 유저정보불러오는 api를 이용해서 api정보를 잘 가지고오면 로그인되어있다고 판단, 아니면 안되어있다고 판단
useEffect(() => {
Expand All @@ -55,8 +55,12 @@ function App() {
}
};
getAuthenticate();
console.log("로그인 되어있는가?", authenticate);
}, [location.key]);
}, [location]);

// 로그인되어있는지 확인
const PrivateRoute = React.useCallback(() => {
return authenticate ? <Outlet /> : <Navigate to="/login" />;
}, [authenticate]);

return (
<>
Expand Down
13 changes: 7 additions & 6 deletions FITple-Frontend/src/components/DeletePopUp/DeletePopUp.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,24 +5,25 @@ import {
DeletePopupText,
PopupButtonContainer,
} from "./DeletePopUp.style";
import { useState } from "react";
import { DeleteClothes } from "../../../data/ClothApi";

const DeletePopUp = ({ onClose, clothId }) => {
console.log("ID확인", clothId);
// 뒤로가기 눌렀을 때
const handlePopupback = () => {
onClose();
};
const [popupdelete, setPopupdelete] = useState(false);
const handlePopupdelete = () => {
setPopupdelete(!popupdelete);
// 삭제하기 눌렀을때
const handlePopupdelete = async () => {
await DeleteClothes(clothId);
onClose();
window.location.reload();
};
return (
<DeletePopup>
<DeletePopupText>정말 삭제하시겠습니까?</DeletePopupText>
<PopupButtonContainer>
<DeletePopupBack onClick={handlePopupback}>뒤로가기</DeletePopupBack>
<DeletePopupDelete onClick={handlePopupdelete}>
<DeletePopupDelete onClick={() => handlePopupdelete()}>
삭제하기
</DeletePopupDelete>
</PopupButtonContainer>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -385,7 +385,6 @@ export const OptionImg = styled.img`

export const SizeWrap = styled.div``;
export const DeleteModal = styled(ReactModal)`
border: 2px solid red;
display: flex;
justify-content: center;
align-items: center;
Expand Down
8 changes: 2 additions & 6 deletions FITple-Frontend/src/pages/LoginPage/LoginPage.jsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
import React, { useState, useEffect } from "react";
import { useNavigate } from "react-router-dom";
import Cookies from "js-cookie"; // 쿠키를 다루기 위한 라이브러리
import logo from "../../../assets/Logo.svg";
import { login } from "../../../data/LoginApi";
import useAuthStore from "../../../data/store/userAuthStore";
import userAuthStore from "../../../data/store/userAuthStore";
import {
LoginPageWrapper,
MainText,
Expand All @@ -21,8 +20,7 @@ function LoginPage() {
const [isButtonActive, setIsButtonActive] = useState(false);
const navigate = useNavigate();

const setToken = useAuthStore((state) => state.setToken); // Zustand 스토어에서 토큰 설정
const { setAuthenticate } = useAuthStore();
const { setAuthenticate } = userAuthStore();

useEffect(() => {
setIsButtonActive(!!(loginId && loginPw));
Expand All @@ -36,8 +34,6 @@ function LoginPage() {
const data = await response.json();

if (response.ok) {
setToken(data.result); // 로그인 성공 시 Zustand 스토어에 토큰을 저장
Cookies.set("authToken", data.result, { expires: 7 }); // 쿠키에 토큰을 저장 (7일간 유지)
setAuthenticate(true);
navigate("/clothes");
} else {
Expand Down
6 changes: 5 additions & 1 deletion FITple-Frontend/src/pages/ProfilePage/ProfilePage.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@ import { useNavigate } from "react-router-dom";
import { getInform } from "../../../data/ProfileApi";
import { logout } from "../../../data/LoginApi";
import Cookies from "js-cookie";
import userAuthStore from "../../../data/store/userAuthStore";

const ProfilePage = () => {
const navigate = useNavigate();
const [selectItem, setSelectItem] = useState(0);
Expand Down Expand Up @@ -51,9 +53,11 @@ const ProfilePage = () => {
// 로그아웃 함수
const handleLogout = async () => {
// 로그아웃을 통해 accessToken, refreshToken 제거
const response = await logout();
await logout();
// authToken 쿠키 삭제
Cookies.remove("authToken");
//zustand persist 로컬스토리지 제거
userAuthStore.persist.clearStorage();
navigate("/");
};
useEffect(() => {
Expand Down

0 comments on commit 9345a5d

Please sign in to comment.