Skip to content

Commit

Permalink
Merge pull request #46 from Soongsil-CoffeeChat/fix/#43-회원가입-수정
Browse files Browse the repository at this point in the history
fix: api 요청 수정
  • Loading branch information
haesol822 authored Nov 13, 2024
2 parents b34ecbb + 40be7e6 commit d5fc1e8
Show file tree
Hide file tree
Showing 8 changed files with 37 additions and 66 deletions.
6 changes: 3 additions & 3 deletions src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -62,9 +62,9 @@ function AppContent() {
<Route path="/mypage/timeselect" element={<TimeSelect />} />
<Route path="/search" element={<Search />} />
<Route path="/mentor-detail/:mentorid" element={<MentorDetails />} />
<Route path="/applycogotime" element={<ApplyCogoTime />} />
<Route path="/applycogomemo" element={<ApplyCogoMemo />} />
<Route path="/applycogocomplete" element={<ApplyCogoComplete />} />
<Route path="/applycogotime/:mentorid" element={<ApplyCogoTime />} />
<Route path="/applycogomemo/:mentorid" element={<ApplyCogoMemo />} />
<Route path="/applycogocomplete/:mentorid" element={<ApplyCogoComplete />} />
<Route path="/cogo" element={<Cogo />} />
<Route path="/cogo/send" element={<SendCogo />} />
<Route path="/cogo/send/detail" element={<SendCogoDetail />} />
Expand Down
19 changes: 10 additions & 9 deletions src/pages/applyCogo/applyCogoComplete.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,21 +14,20 @@ import {
} from "../../components/global.styles";
import BackButton from "../../components/button/backButton";
import moment from "moment";
import { useNavigate } from "react-router-dom";
import { useNavigate, useParams } from "react-router-dom";
import Coffee from "../../assets/Coffee.svg";
import axiosInstance from "../../apis/axiosInstance"; // axiosInstance 추가

export default function ApplyCogoComplete() {
const navigate = useNavigate();
const { mentorid } = useParams();
const [isLoading, setIsLoading] = useState<boolean>(false); // 로딩 상태 추가

const handleNextButton = async () => {
// 로딩 상태 시작
setIsLoading(true);

try {
// localStorage에서 데이터 불러오기
const mentorIdStr = localStorage.getItem("mentorId");
const mentorIdStr = mentorid
const possibleDateIdStr = localStorage.getItem("possible_date_id");
const memoText = localStorage.getItem("memoText");

Expand All @@ -50,21 +49,23 @@ export default function ApplyCogoComplete() {
return;
}

try {

// API 요청을 위한 페이로드 준비
const payload = {
mentorId: mentorId,
possibleDateId: possibleDateId,
memo: memoText,
};

console.log(payload)
console.log(payload);
// API 요청 보내기 (예시 엔드포인트 사용)
const response = await axiosInstance.post("/applications", payload);

// 요청 성공 시 처리
console.log("API 응답:", response.data);
alert("COGO 신청이 완료되었습니다!");

// 필요 시 localStorage 데이터 정리
localStorage.removeItem("mentorId");
localStorage.removeItem("possible_date_id");
Expand All @@ -90,9 +91,9 @@ export default function ApplyCogoComplete() {
<S.Title>멘토님과의 매칭이 곧 이루어질 예정이에요!</S.Title>
<S.Subtitle>COGO를 하면서 많은 성장을 기원해요!</S.Subtitle>
<S.SecondContainer>
<S.CoffeeImg src={Coffee} alt="Coffee"/>
<S.CompleteButton
onClick={handleNextButton}
<S.CoffeeImg src={Coffee} alt="Coffee" />
<S.CompleteButton
onClick={handleNextButton}
disabled={isLoading} // 로딩 중 버튼 비활성화
>
{isLoading ? "처리 중..." : "코고 신청 완료하기"}
Expand Down
5 changes: 3 additions & 2 deletions src/pages/applyCogo/applyCogoMemo.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,12 @@ import {
Title,
} from "../../components/global.styles";
import BackButton from "../../components/button/backButton";
import { useNavigate } from "react-router-dom";
import { useNavigate, useParams } from "react-router-dom";

export default function ApplyCogoMemo() {
const [memoText, setMemoText] = useState<string>(""); // 메모 텍스트 상태
const navigate = useNavigate();
const { mentorid } = useParams();

// 글자 수를 변경하는 함수
const handleMemoChange = (event: React.ChangeEvent<HTMLTextAreaElement>) => {
Expand All @@ -24,7 +25,7 @@ export default function ApplyCogoMemo() {
console.log(memoText);
localStorage.setItem("memoText", memoText);

navigate("/applyCogoComplete");
navigate(`/applyCogoComplete/${mentorid}`);
};

return (
Expand Down
27 changes: 7 additions & 20 deletions src/pages/applyCogo/applyCogoTime.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import {
} from "../../components/global.styles";
import BackButton from "../../components/button/backButton";
import moment from "moment";
import { useNavigate } from "react-router-dom";
import { useNavigate, useParams } from "react-router-dom";
import axiosInstance from "../../apis/axiosInstance";

type PossibleDate = {
Expand Down Expand Up @@ -42,26 +42,13 @@ export default function ApplyCogoTime() {
);
const [selectedTime, setSelectedTime] = useState<string | null>(null);
const [timesForDate, setTimesForDate] = useState<string[]>([]);
const [mentorId, setMentorId] = useState<number>(0);
const { mentorid } = useParams();
const [possibleDates, setPossibleDates] = useState<PossibleDatesData>([]);
const navigate = useNavigate();

useEffect(() => {
axiosInstance
.get(`/users`)
.then((response) => {
console.log(response.data.content);
setMentorId(response.data.content.mentorId);
localStorage.setItem("mentorId", mentorId.toString());
})
.catch((error) => {
console.error("멘토아이디 조회 실패: ", error);
});
}, []);

const fetchPossibleDates = async () => {
try {
const response = await axiosInstance.get(`/possibleDates/${mentorId}`);
const response = await axiosInstance.get(`/possibleDates/${mentorid}`);
console.log("possibleDates get: ", response.data.content);
setPossibleDates(response.data.content || []);
} catch (error) {
Expand All @@ -72,10 +59,8 @@ export default function ApplyCogoTime() {
};

useEffect(() => {
if (mentorId) {
fetchPossibleDates();
}
}, [mentorId]);
}, []);

// selectedDate 또는 possibleDates가 변경될 때 timesForDate 업데이트
useEffect(() => {
Expand Down Expand Up @@ -163,14 +148,16 @@ export default function ApplyCogoTime() {
console.warn("No matching possible_date_id found.");
}

navigate("/applyCogoMemo", {
navigate(`/applyCogoMemo/${mentorid}`, {
state: {
selectedDate: formattedSelectedDate,
selectedTime,
},
});
};

console.log(selectedDate, selectedTime);

return (
<S.Container>
<Header>
Expand Down
2 changes: 1 addition & 1 deletion src/pages/mentorDetails/mentorDetails.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ export default function MentorDetails() {
}, []);

const handleApplyBtnClick = () => {
navigate("/applycogotime");
navigate(`/applycogotime/${mentorid}`);
};

const formatTextWithLineBreaks = (text: string) => {
Expand Down
23 changes: 9 additions & 14 deletions src/pages/mypage/mypage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ export default function MyPage() {
const response = await axiosInstance.delete("/users");
console.log(response.data);
} catch (error) {
console.error('Error deleting account:', error);
console.error("Error deleting account:", error);
alert("회원 탈퇴가 완료되었습니다.");
navigate("/login");
}
Expand All @@ -74,24 +74,21 @@ export default function MyPage() {
const file = e.target.files?.[0];
if (!file) return;

// 클라이언트 측에서 파일 크기 및 형식 검증
const allowedTypes = ["image/jpeg", "image/jpg", "image/png"];
if (!allowedTypes.includes(file.type)) {
alert("이미지 형식만 업로드할 수 있습니다. (jpeg, jpg, png)");
return;
}

if (file.size > 5 * 1024 * 1024) {
// 5MB 제한
alert("파일 크기가 너무 큽니다. 5MB 이하의 이미지를 선택해주세요.");
return;
}

setIsUploading(true); // 업로드 시작
setUploadError(""); // 기존 에러 초기화
setIsUploading(true);
setUploadError("");

try {
// 1단계: S3로 이미지 업로드
const directory = "v2";
const formData = new FormData();
formData.append("image", file);
Expand All @@ -109,19 +106,14 @@ export default function MyPage() {
console.log("S3 Response:", s3Response.data);

if (s3Response.status === 201) {
// S3 업로드 성공, 응답에서 이미지 URL 추출
// 실제 응답 구조에 맞게 수정 필요
let imageUrl: string | undefined;

if (s3Response.data.content.savedUrl) {
imageUrl = s3Response.data.content.savedUrl;
} else if (s3Response.data.content.additionalProp1) {
imageUrl = s3Response.data.content.additionalProp1;
} else {
throw new Error("이미지 URL을 받아오지 못했습니다.");
}

// 2단계: 사용자 프로필에 이미지 URL 업데이트
const pictureResponse = await axiosInstance.put(
"/users/picture",
imageUrl
Expand All @@ -130,7 +122,7 @@ export default function MyPage() {
if (pictureResponse) {
console.log(
"프로필 이미지 업데이트 성공:",
pictureResponse.data.content.picture.slice(1,-1)
pictureResponse.data.content.picture.slice(1, -1)
);
const imageUrl = pictureResponse.data.content.picture;
setUserData((prevData) =>
Expand All @@ -156,6 +148,7 @@ export default function MyPage() {
}
};

console.log("유저정보", userData?.picture);
return (
<Container>
<input
Expand All @@ -168,7 +161,9 @@ export default function MyPage() {
/>

<S.HeaderContainer>
<S.MenotorName>{userData?.name} 멘토님</S.MenotorName>
<S.MenotorName>
{userData?.name} {userData?.role === "MENTEE" ? "멘티님" : "멘토님"}
</S.MenotorName>
</S.HeaderContainer>
<S.BodyContainer>
<S.ProfileContainer>
Expand All @@ -180,7 +175,7 @@ export default function MyPage() {
<>
<S.ProfileLayer />
<S.ProfileImg
src={userData.picture.slice(1,-1)}
src={userData.picture.slice(1, -1)}
alt="Profile"
/>
</>
Expand Down
3 changes: 2 additions & 1 deletion src/pages/mypage/myprofile/myprofile.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -249,7 +249,8 @@ export default function MyProfile() {
axiosInstance
.patch("/users", updatedData)
.then((response) => {
console.log("사용자 정보 업데이트 성공:", response.data);
console.log(updatedData);
console.log("사용자 정보 업데이트 성공:", response.data.content);
setIsEditing(false); // 저장 후 편집 모드 종료
alert("정보가 성공적으로 저장되었습니다.");
setUserData(response.data.content); // 서버에서 반환한 최신 데이터로 업데이트
Expand Down
18 changes: 2 additions & 16 deletions src/pages/mypage/timeselect/timeselect.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ export default function TimeSelect() {

const fetchPossibleDates = async () => {
try {
const response = await axiosInstance.get(`/possibleDates/${mentorId}`);
const response = await axiosInstance.get(`/possibleDates`);
console.log("possibleDates get: ", response.data.content);
setPossibleDates(response.data.content || []);
} catch (error) {
Expand All @@ -61,23 +61,9 @@ export default function TimeSelect() {
};

useEffect(() => {
axiosInstance
.get(`/users`)
.then((response) => {
console.log(response.data.content);
setMentorId(response.data.content.mentorId);
})
.catch((error) => {
console.error("Failed to fetch user data:", error);
});
fetchPossibleDates();
}, []);

useEffect(() => {
if (mentorId) {
fetchPossibleDates();
}
}, [mentorId]);

const handleDateChange = (value: Date) => {
const dateString = moment(value).format("YYYY-MM-DD");

Expand Down

0 comments on commit d5fc1e8

Please sign in to comment.