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

✅ Test: API 연결 코드 확인 #51

Merged
merged 6 commits into from
Sep 11, 2024
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
34 changes: 21 additions & 13 deletions src/components/ChocoCheck/ChocoCheck22.jsx
Original file line number Diff line number Diff line change
@@ -1,30 +1,34 @@
import * as S from "./ChocoChoco22";
import { CHOCOLATES } from "../../constants/Chocolates/data";
import { useState } from "react";
import { useNavigate } from "react-router-dom";
// import { instance } from "../../apis/instance";

const ChocoCheck22 = ({ currentPage, itemsPerPage }) => {
const ChocoCheck22 = ({ currentPage, itemsPerPage, chocoData, error }) => {
const [selectedChocoId, setSelectedChocoId] = useState(null);
const navigate = useNavigate();

// chocoType 값을 이미지 경로로 매핑하는 객체
const imageMap = {
1: "/assets/images/Chocolates/Chocolate_1.svg",
2: "/assets/images/Chocolates/Chocolate_2.svg",
3: "/assets/images/Chocolates/Chocolate_3.svg",
4: "/assets/images/Chocolates/Chocolate_4.svg",
5: "/assets/images/Chocolates/Chocolate_5.svg",
6: "/assets/images/Chocolates/Chocolate_6.svg",
};

// 현재 페이지에 표시될 아이템 계산
const startIndex = (currentPage - 1) * itemsPerPage;
const currentItems = CHOCOLATES.slice(startIndex, startIndex + itemsPerPage);
const currentItems = chocoData.slice(startIndex, startIndex + itemsPerPage);

const handleChocoClick = (id) => {
setSelectedChocoId(id);
console.log("Clicked Choco Id:", id);
navigate(`/detailletter/${id}`);
};

// const getchocolist = async () => {
// try {
// const response = await instance.get("/api/choco?page={page}");
// console.log("success", response.data);
// } catch (error) {
// console.error("fail", error);
// }
// };
if (error) {
return <p>{error}</p>; // 오류 메시지 표시
}

return (
<S.ListCheck>
Expand All @@ -34,7 +38,11 @@ const ChocoCheck22 = ({ currentPage, itemsPerPage }) => {
onClick={() => handleChocoClick(item.id)}
selected={selectedChocoId === item.id}
>
<S.Image src={item.src} alt={`Chocolate ${item.id}`} />
{/* chocoType 값을 사용하여 이미지 경로 매핑 */}
<S.Image
src={imageMap[item.chocoType] || "/images/chocolates/default.png"}
alt={`Chocolate ${item.id}`}
/>
</S.Card>
))}
</S.ListCheck>
Expand Down
26 changes: 22 additions & 4 deletions src/components/ChocoCheck/ChocoCheck33.jsx
Original file line number Diff line number Diff line change
@@ -1,21 +1,35 @@
import * as S from "./styled";
import { CHOCOLATES } from "../../constants/Chocolates/data";
import { useState } from "react";
import { useNavigate } from "react-router-dom";

const ChocoCheck33 = ({ currentPage, itemsPerPage }) => {
const ChocoCheck33 = ({ currentPage, itemsPerPage, chocoData, error }) => {
const [selectedChocoId, setSelectedChocoId] = useState(null);
const navigate = useNavigate();

// chocoType 값을 이미지 경로로 매핑하는 객체
const imageMap = {
1: "/assets/images/Chocolates/Chocolate_1.svg",
2: "/assets/images/Chocolates/Chocolate_2.svg",
3: "/assets/images/Chocolates/Chocolate_3.svg",
4: "/assets/images/Chocolates/Chocolate_4.svg",
5: "/assets/images/Chocolates/Chocolate_5.svg",
6: "/assets/images/Chocolates/Chocolate_6.svg",
};

// 현재 페이지에 표시될 아이템 계산
const startIndex = (currentPage - 1) * itemsPerPage;
const currentItems = CHOCOLATES.slice(startIndex, startIndex + itemsPerPage);
const currentItems = chocoData.slice(startIndex, startIndex + itemsPerPage);

const handleChocoClick = (id) => {
setSelectedChocoId(id);
console.log("Clicked Choco Id:", id);
navigate(`/detailletter/${id}`);
};

if (error) {
return <p>{error}</p>; // 오류 메시지 표시
}

return (
<S.ListCheck>
{currentItems.map((item) => (
Expand All @@ -24,7 +38,11 @@ const ChocoCheck33 = ({ currentPage, itemsPerPage }) => {
onClick={() => handleChocoClick(item.id)}
selected={selectedChocoId === item.id}
>
<S.Image src={item.src} alt={`Chocolate ${item.id}`} />
{/* chocoType 값을 사용하여 이미지 경로 매핑 */}
<S.Image
src={imageMap[item.chocoType] || "/images/chocolates/default.png"}
alt={`Chocolate ${item.id}`}
/>
</S.Card>
))}
</S.ListCheck>
Expand Down
2 changes: 1 addition & 1 deletion src/components/ChocoCheck/ChocoChoco22.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,6 @@ export const ListCheck = styled.div`
export const Card = styled.div``;

export const Image = styled.img`
width: 80px;
width: 100px;
padding: 5px;
`;
6 changes: 4 additions & 2 deletions src/components/ChocoCheck/styled.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,14 @@ export const ListCheck = styled.div`
display: grid;
grid-template-columns: repeat(3, 1fr);
position: absolute;
top: 235px;
top: 200px;
`;

export const Card = styled.div``;

export const Image = styled.img`
width: 83px;
width: 100px;
padding: 5px;
`;

export const PageIndicator = styled.div``;
57 changes: 42 additions & 15 deletions src/pages/ChocoList/ChocoList.jsx
Original file line number Diff line number Diff line change
@@ -1,19 +1,44 @@
import { useState } from "react";
import { useState, useEffect } from "react";
import * as S from "./styled";
import LOGO from "../../assets/images/mainLogo.svg";
import ChocoCheck33 from "../../components/ChocoCheck/ChocoCheck33";
import ChocoCheck22 from "../../components/ChocoCheck/ChocoCheck22";
import { NextBtn } from "../../components/common/Button/NextBtn";
import { BackBtn } from "../../components/common/Button/BackBtn";
import { CHOCOLATES } from "../../constants/Chocolates/data";
import { instance } from "../../apis/instance";

const ChocoList = () => {
const [currentPage, setCurrentPage] = useState(1);
const [selectedBoxId, setSelectedBoxId] = useState(1); // 초기값 1로 설정
const [selectedBoxId, setSelectedBoxId] = useState(1);
const [chocoData, setChocoData] = useState([]);
const [totalPages, setTotalPages] = useState(1);
const [error, setError] = useState(null);

const ITEMS_PER_PAGE = selectedBoxId === 4 ? 6 : 9; // box4일 때는 6, 나머지는 9로 설정
const ITEMS_PER_PAGE = selectedBoxId === 4 ? 6 : 9;

const totalPages = Math.ceil(CHOCOLATES.length / ITEMS_PER_PAGE);
const getChocoList = async (page) => {
try {
const response = await instance.get(`/api/choco?page=${page}`);
console.log("API Response:", response.data);

if (response.data && response.data.message === "OK") {
const { chocoList, totalPage } = response.data.result;
setChocoData(chocoList);
setTotalPages(totalPage);
setError(null);
} else {
console.error("Unexpected response structure:", response.data);
setError("데이터를 불러오는 중 문제가 발생했습니다.");
}
} catch (error) {
console.error("Failed to fetch choco data", error);
setError("네트워크 오류가 발생했습니다. 다시 시도해주세요.");
}
};

useEffect(() => {
getChocoList(currentPage);
}, [currentPage]);

const handleNextPage = () => {
if (currentPage < totalPages) {
Expand All @@ -35,9 +60,19 @@ const ChocoList = () => {
return (
<S.Wrapper $selectedBoxId={selectedBoxId}>
{selectedBoxId === 4 ? (
<ChocoCheck22 currentPage={currentPage} itemsPerPage={ITEMS_PER_PAGE} />
<ChocoCheck22
currentPage={currentPage}
itemsPerPage={ITEMS_PER_PAGE}
chocoData={chocoData}
error={error}
/>
) : (
<ChocoCheck33 currentPage={currentPage} itemsPerPage={ITEMS_PER_PAGE} />
<ChocoCheck33
currentPage={currentPage}
itemsPerPage={ITEMS_PER_PAGE}
chocoData={chocoData}
error={error}
/>
)}
<S.Logo src={LOGO} alt="Logo" />
<S.Name>[김연진]의 초콜릿 상자</S.Name>
Expand All @@ -49,14 +84,6 @@ const ChocoList = () => {
disabled={currentPage === totalPages}
/>
</S.ButtonContainer>
임시로 상자 선택 버튼 추가
<div>
{[1, 2, 3, 4, 5, 6].map((id) => (
<button key={id} onClick={() => handleBoxChange(id)}>
Set Box {id}
</button>
))}
</div>
</S.Wrapper>
);
};
Expand Down
7 changes: 6 additions & 1 deletion src/pages/ChocoList/styled.js
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ export const Wrapper = styled.div`
flex-direction: column;
justify-content: center;
align-items: center;
width: 100%;
width: 390px;
height: 667px;
background-image: ${({ $selectedBoxId }) =>
getBackgroundImage($selectedBoxId)};
Expand Down Expand Up @@ -78,3 +78,8 @@ export const PageIndicator = styled.div`
position: absolute;
top: 530px;
`;

export const Test = styled.div`
position: absolute;
top: 500px;
`;
76 changes: 61 additions & 15 deletions src/pages/DetailLetter/DetailLetter.jsx
Original file line number Diff line number Diff line change
@@ -1,13 +1,18 @@
// 주석 정리한 버전
import { useNavigate, useParams } from "react-router-dom";
import * as S from "./styled";
import HeartBackG from "../../components/common/Heartbackground/heartBackG";
import { LETTERS } from "../../constants/letters/data";
import { useState, useEffect } from "react";
import { instance } from "../../apis/instance";
import CloseButton from "../../assets/images/CloseButton.svg";
import DeleteButton from "../../assets/images/DeleteButton.svg";
import { LETTERS } from "../../constants/letters/data";

const DetailLetter = () => {
const navigate = useNavigate();
const { id } = useParams();
const [letterData, setLetterData] = useState(null);
const [error, setError] = useState(null);

const chocoToLetterMapping = {
1: 1,
Expand All @@ -17,35 +22,76 @@ const DetailLetter = () => {
5: 5,
6: 6,
};
// 초코 아이디랑 편지지 디자인 맵핑...

useEffect(() => {
const fetchLetterData = async () => {
try {
const response = await instance.get(`/api/choco/${id}`);
console.log("API Response:", response.data);

const letterId = chocoToLetterMapping[Number(id)];
if (response.data && response.data.message === "OK") {
setLetterData(response.data.result);
setError(null);
} else {
console.error("Unexpected response structure:", response.data);
setError("데이터를 불러오는 중 문제가 발생했습니다.");
}
} catch (error) {
console.error("Failed to fetch letter data", error);
if (error.response) {
const { message } = error.response.data;
setError(message || "알 수 없는 오류가 발생했습니다.");
} else {
setError("네트워크 오류가 발생했습니다. 다시 시도해주세요.");
}
}
};

const selectedLetter = LETTERS.find((letter) => letter.id === letterId);
fetchLetterData();
}, [id]);

const handleDeleteClick = () => {
navigate(-1); // 뒤로 가기
const letterDesignId = letterData
? chocoToLetterMapping[letterData.chocoId]
: 1;
const selectedLetter = LETTERS.find((letter) => letter.id === letterDesignId);

// 아래로는 삭제 코드
const handleDeleteClick = async () => {
try {
const response = await instance.delete(`/api/choco/${id}`);
if (response.data && response.data.message === "OK") {
alert("삭제가 완료되었습니다.");
navigate(-1);
} else {
console.error("Unexpected response structure:", response.data);
alert("삭제에 실패했습니다.");
}
} catch (error) {
console.error("Failed to delete data", error);
alert("삭제 중 오류가 발생했습니다. 다시 시도해주세요.");
}
};

return (
<>
<S.DetailLetter>
<HeartBackG />
<S.LetterPosition>
{selectedLetter ? (
{error ? (
<p>{error}</p>
) : letterData ? (
<>
<S.Letter
src={selectedLetter.src}
alt={`Letter ${selectedLetter.id}`}
src={selectedLetter ? selectedLetter.src : ""}
alt={`Letter ${letterData.id}`}
/>

<S.textContainer>
<p className="contents">
안녕하세용가리 fjdkfjdkjfdlfjdlfjdljfdljfdf
</p>
<div className="nickName">from.ㅋㅋ</div>
<p className="contents">{letterData.contents}</p>
<div className="nickName">from. {letterData.nickname}</div>
</S.textContainer>
<S.CloseButton src={CloseButton} onClick={handleDeleteClick} />
<S.DeleteButton src={DeleteButton} />
<S.CloseButton src={CloseButton} onClick={() => navigate(-1)} />
<S.DeleteButton src={DeleteButton} onClick={handleDeleteClick} />
</>
) : (
<p>편지지를 찾을 수 없습니다</p>
Expand Down