Skip to content
Open
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
4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

46 changes: 43 additions & 3 deletions src/app/checkout/page.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
// CheckoutPage
import { useState } from "react";
import { useState, useEffect, use } from "react";
import { ProductItem } from "@/types/Product";

interface CheckoutItem {
Expand All @@ -9,13 +9,53 @@ interface CheckoutItem {
// 과제 3
export default function CheckoutPage() {
const [items, setItems] = useState<CheckoutItem[]>([]);

useEffect(() => {
const storedItems = localStorage.getItem("checkoutItems");
if (storedItems) {
const parsedItems: CheckoutItem[] = JSON.parse(storedItems);
setItems(parsedItems);
parsedItems.forEach((item) => { localStorage.removeItem(item.product.productId); });
localStorage.removeItem("checkoutItems");
}
}, []);

const total = items.reduce((sum, item) => sum + Number(item.product.lprice) * item.quantity, 0);
// 3.1. 결제하기 구현
return (
<div className="p-6 max-w-3xl mx-auto bg-white rounded shadow mt-6">
<h1 className="text-2xl font-bold mb-4">✅ 결제가 완료되었습니다!</h1>
{/* 3.1. 결제하기 구현 */}
<div></div>
{items.length === 0 ? (
<p>결제한 아이템이 없습니다.</p>
):(
<>
<ul className="space-y-4">
{items.map((item, index) => (
<li key={index} className="border-b pb-2">
<p
className="font-medium"
dangerouslySetInnerHTML={{ __html: item.product.title }}
></p>
<p className="text-sm text-gray-600">
수량: {item.quantity}개 / 가격:{" "}
{(Number(item.product.lprice) * item.quantity).toLocaleString()}원
</p>
</li>
))}
</ul>
<div className="text-right font-bold mt-2">
총 결제 금액: {total.toLocaleString()}원
</div>
</>
)}

{/* 3.2. 홈으로 가기 버튼 구현 */}
<div className="mt-6 text-center">
<a href="/" className="inline-block px-4 py-2 bg-blue-400 text-white rounded-md hover:bg-blue-500 hover:shadow-lg transition cursor-pointer">
홈으로 가기
</a>
</div>
</div>
);
}
}
7 changes: 5 additions & 2 deletions src/app/layout.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import type { Metadata } from "next";
import { Geist, Geist_Mono } from "next/font/google";
import { UserProvider } from "@/context/UserContext";
import "./globals.css";

const geistSans = Geist({
Expand Down Expand Up @@ -27,8 +28,10 @@ export default function RootLayout({
<body
className={`${geistSans.variable} ${geistMono.variable} antialiased`}
>
{children}
<UserProvider>
{children}
</UserProvider>
</body>
</html>
);
}
}
24 changes: 20 additions & 4 deletions src/app/mypage/page.tsx
Original file line number Diff line number Diff line change
@@ -1,14 +1,30 @@
'use client';

import { useUser } from "@/context/UserContext";
import Header from "@/component/layout/Header";
import Link from "next/link";

// 과제 1: 마이페이지 구현
export default function MyPage() {
// 1.1. UserContext를 활용한 Mypage 구현 (UserContext에 아이디(userId: string), 나이(age: number), 핸드폰번호(phoneNumber: string) 추가)

const { user } = useUser();
return (
<div className="flex flex-col items-center min-h-screen bg-gray-50">
{/* 1.2. Header Component를 재활용하여 Mypage Header 표기 (title: 마이페이지) */}
<p>마이페이지</p>
<Header title = "마이페이지"/>
{/* Mypage 정보를 UserContext 활용하여 표시 (이름, 아이디, 나이, 핸드폰번호 모두 포함) */}

<div className="p-6 max-w-3xl mx-auto bg-white rounded shadow mt-6">
<h2 className="text-2xl font-bold mb-4">회원 정보</h2>
<p className="text-gray-700 mb-2"><strong>이름: </strong>{user.name}</p>
<p className="text-gray-700 mb-2"><strong>아이디: </strong>{user.userId}</p>
<p className="text-gray-700 mb-2"><strong>나이: </strong>{user.age}</p>
<p className="text-gray-700"><strong>전화번호: </strong>{user.phoneNumber}</p>
</div>
{/* 1.3. 홈으로 가기 버튼 구현(Link or Router 활용) */}
<Link href="/"
className="mt-6 px-4 py-2 rounded-md bg-blue-400 text-white border border-gray-300 hover:bg-blue-500 hover:shadow-lg transition cursor-pointer">
홈으로 가기
</Link>
</div>
);
}
}
18 changes: 15 additions & 3 deletions src/app/search/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,19 +5,31 @@ import Footer from "../../component/layout/Footer";
import SearchInput from "../../component/search/SearchInput";
import ProductCart from "../../component/shopping/ProductCart";
import { useUser } from "../../context/UserContext";
import { useEffect } from "react";
import { useEffect, useState } from "react";
import { useSearch } from "../../context/SearchContext";

export default function SearchHome() {
const { user, setUser } = useUser();
const { result } = useSearch();

const [cart, setCart] = useState<{ [productId: string]: number }>({});
const [showCart, setShowCart] = useState(false);

// 페이지 최초 렌더링 될 때, setUser로 이름 설정
useEffect(() => {
// 학번 + 이름 형태로 작성 (ex. 2025***** 내이름 )
setUser({ name: "" });
setUser({
name: "202302547 나소진",
userId: "sjna",
age: 24,
phoneNumber: "010-0000-0000"
});
}, []);

useEffect(() => {
setShowCart(Object.keys(cart).length > 0);
}, [cart]);

return (
<div className="flex justify-center">
<div className="w-[80%]">
Expand All @@ -27,4 +39,4 @@ export default function SearchHome() {
</div>
</div>
);
}
}
16 changes: 13 additions & 3 deletions src/component/search/SearchInput.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
"use client";
import { useEffect, useRef } from "react";
import { useSearch } from "@/context/SearchContext";

export default function SearchInput() {
const inputRef = useRef<HTMLInputElement>(null);
const { query, setQuery, setResult } = useSearch();

// 검색 기능
Expand All @@ -19,14 +21,22 @@ export default function SearchInput() {
};

// 2.2. SearchInput 컴포넌트가 최초 렌더링 될 때, input tag에 포커스 되는 기능
const handleInputChange = () => {};
const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
setQuery(e.target.value);
};

// 과제 1-2-3: 페이지 최초 렌더링 시, input에 포커스 되는 기능 (useRef)

useEffect(() => {
if (inputRef.current) {
inputRef.current.focus();
}
}, []);

return (
<div className="flex justify-center items-center gap-2 mt-4">
<input
type="text"
ref={inputRef}
value={query}
onChange={handleInputChange}
placeholder="검색어를 입력하세요"
Expand All @@ -40,4 +50,4 @@ export default function SearchInput() {
</button>
</div>
);
}
}
16 changes: 14 additions & 2 deletions src/component/shopping/CartList.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,19 @@ export default function CartList({ cart, products, onRemove }: Props) {
);

// 2.4 결제하기: "결제하기" 버튼을 클릭하면, 현재 장바구니에 담긴 상품을 확인해 **localStorage**에 저장 후, 결제완료(/checkout) 페이지로 이동한다.
const handleCheckout = () => {};
const handleCheckout = () => {
const checkoutData = cartItems.map((item) => ({
product: {
productId: item.productId,
title: item.title,
lprice: item.lprice,
},
quantity: item.quantity,
}));

localStorage.setItem("checkoutItems", JSON.stringify(checkoutData));
window.location.href = "/checkout";
};

return (
<div className="p-4 bg-white rounded shadow mt-6">
Expand Down Expand Up @@ -68,4 +80,4 @@ export default function CartList({ cart, products, onRemove }: Props) {
</div>
</div>
);
}
}
18 changes: 15 additions & 3 deletions src/component/shopping/ProductCart.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,15 +20,27 @@ export default function ProductCart({ items }: { items: ProductItem[] }) {
};

/* 과제 2-3: Cart 아이템 지우기 */
const handleRemoveFromCart = () => {};
const handleRemoveFromCart = (productId: string) => {
const updatedCart = Object.fromEntries(
Object.entries(cart).filter(([id, _]) => id !== productId)
);
setCart(updatedCart);
localStorage.removeItem(productId);
};

return (
<div className="p-10">
{/* 상품 리스트 */}
<ProductList items={items} onAddToCart={handleAddToCart} />
{/* 장바구니 */}
{/* 2.1. 조건부 카트 보이기: 카트에 담긴 상품이 없으면 카트가 보이지 않고, 카트에 담긴 물건이 있으면 카트가 보인다 */}
<CartList cart={cart} products={items} onRemove={handleRemoveFromCart} />
{Object.keys(cart).length > 0 && (
<CartList
cart={cart}
products={items}
onRemove={handleRemoveFromCart}
/>
)}
</div>
);
}
}
12 changes: 10 additions & 2 deletions src/context/UserContext.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,9 @@ interface User {
name: string;
// age: number
// 추가하고 싶은 속성들 ...
userId: string;
age: number;
phoneNumber: string;
}
// UserContextType
interface UserContextType {
Expand All @@ -22,7 +25,12 @@ export const UserContext = createContext<UserContextType | undefined>(

// 2. Provider 생성
export const UserProvider = ({ children }: { children: ReactNode }) => {
const [user, setUser] = useState<User>({ name: "" });
const [user, setUser] = useState<User>({
name: "202302547 나소진",
userId: "sjna",
age: 24,
phoneNumber: "010-0000-0000"
});
return (
<UserContext.Provider value={{ user, setUser }}>
{children}
Expand All @@ -38,4 +46,4 @@ export const useUser = () => {
throw new Error("error");
}
return context;
};
};