Skip to content

Commit

Permalink
✨ feat: 챌린지 뽑기 api 연동
Browse files Browse the repository at this point in the history
- 백엔드 api 중 챌린지를 뽑는 api를 연동합니다

by Hah-nna #14
  • Loading branch information
Hah-nna committed Mar 29, 2024
1 parent e856ada commit 8ae7d60
Showing 1 changed file with 80 additions and 26 deletions.
106 changes: 80 additions & 26 deletions src/pages/CreateChallengePage/index.tsx
Original file line number Diff line number Diff line change
@@ -1,61 +1,111 @@
import StatusBarLayout from "../../components/layout/StatusBarLayout";
import testImg from "../../assets/challengeImg_test.svg";
import getCurrentDateTime from "../../utils/utils";
import { useRecoilState } from "recoil";
import { challengeLoadingState } from "../../store/challengeLoadingState";
import { useEffect } from "react";
import Roulette from "../../assets/roulette.svg?react";
import { useNavigate } from "react-router-dom";
import DownloadIcon from "../../assets/icons/downloadIcon.svg?react";
import axios, { AxiosError } from "axios";
import Cookies from "js-cookie";
import { userDataState } from "../../store/userDataState";
import roulette from "../../assets/roulette.gif";

const CreateChallengePage = () => {
const { currentYear, currentMonth, currentDate, currentHour, currentMinute } =
getCurrentDateTime();
const [challengeLoading, setChallengeLoading] = useRecoilState(
challengeLoadingState
);
const navigate = useNavigate();
const [userData, setUserData] = useRecoilState(userDataState);
const accessToken = Cookies.get("accessToken");

const mainApi = async () => {
setChallengeLoading(true); // api 호출 전에 true로 변경하여 로딩화면 띄우기
try {
// 시뮬레이션을 위한 임시 promise 함수
const simulateFetch = () => {
return new Promise((resolve) => {
setTimeout(() => {
resolve({ data: "fake data" }); // 2초 후에 가짜 데이터 반환
}, 500);
});
};

const response = await simulateFetch();
const body = { category: "랜덤" };
console.log("body", body);
try {
setChallengeLoading(true);
await axios
.post("https://today-challenge.site/challenge/draw", body, {
headers: { Authorization: `Bearer ${accessToken}` },
})
.then((res) => {
setChallengeLoading(false);
const {
memberName,
memberProfile,
startTime,
expireTime,
challengeTitle,
challengeImg,
} = res.data;

console.log("mainData", response);
setChallengeLoading(false); // api 호출 완료 됐을 때 false로 변경하여 로딩화면 숨김처리
} catch (error) {
window.alert(error);
setUserData({
memberName,
memberProfile,
startTime,
expireTime,
challengeTitle,
challengeImg,
completeTime: "",
});
console.log("res", res);
});
} catch (err) {
console.log("err", err);
navigate("/error");
}
};

useEffect(() => {
mainApi();
}, []);

const date = new Date(userData.startTime);

const year = date.getFullYear();
const month = date.getMonth() + 1;
const day = date.getDate();
const hours = date.getHours();
const minutes = date.getMinutes();

const tryChallengeHandler = async () => {
try {
await axios
.post("https://today-challenge.site/challenge/try", null, {
headers: { Authorization: `Bearer ${accessToken}` },
})
.then(() => {
navigate("/my-page");
});
} catch (err) {
const axiosError = err as AxiosError;
if (
axiosError.response?.data === "이미 도전 중인 챌린지가 있습니다." ||
axiosError.response?.status === 409
) {
navigate("/have-challenge");
} else {
console.log("err", err);
navigate("/error");
}
}
};

return (
<StatusBarLayout
color="white"
showButton={challengeLoading ? false : true}
leftBtnText="취소"
rightBtnText="도전하기"
leftBtnClick={() => navigate("/")}
rightBtnClick={() => navigate("/my-page/:id")}
rightBtnClick={tryChallengeHandler}
>
<div className="flex flex-col justify-center items-center h-[calc(100vh-58px-34px)] w-full">
{challengeLoading ? (
<div className=" text-center">
<Roulette />
<img src={roulette} alt="roulette" />
<div className="pt-[34px]">
<h1>챌린저 님의 챌린지를</h1>
<h1>{`${userData.memberName} 님의 챌린지를`}</h1>
<h1>뽑고 있어요</h1>
</div>
</div>
Expand All @@ -68,18 +118,22 @@ const CreateChallengePage = () => {

<div className="pt-12 pb-20 relative">
{/* 주 이미지 */}
<img src={testImg} alt="test" className="w-[305px] h-[385px]" />
<img
src={userData.challengeImg}
alt="challengeImg"
className="w-[305px] h-[385px]"
/>

{/* 프로필 사진과 텍스트를 묶은 컨테이너 */}
<div className="absolute flex items-center gap-2 left-[30px] top-[80px]">
<img
src={testImg}
src={userData.memberProfile}
alt="profile"
className="w-8 h-8 rounded-full"
/>
<div>
<h3 className="font-semibold">챌린져</h3>
<p className="body-s text-gray-700">{`${currentYear}${currentMonth}${currentDate}${currentHour}:${currentMinute}`}</p>
<h3 className="font-semibold">{userData.memberName}</h3>
<p className="body-s text-gray-700">{`${year}${month}${day}${hours}:${minutes}`}</p>
</div>
</div>

Expand Down

0 comments on commit 8ae7d60

Please sign in to comment.