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
60 changes: 53 additions & 7 deletions src/app/checkout/page.tsx
Original file line number Diff line number Diff line change
@@ -1,21 +1,67 @@
// CheckoutPage
import { useState } from "react";
"use client";

import { useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import { ProductItem } from "@/types/Product";

interface CheckoutItem {
product: ProductItem;
productId: string;
title: string;
lprice: string;
quantity: number;
}
// 과제 3

// 과제 3
export default function CheckoutPage() {
const [items, setItems] = useState<CheckoutItem[]>([]);
// 3.1. 결제하기 구현
const router = useRouter();

// 3.1. 결제하기 구현: localStorage에서 불러오기
useEffect(() => {
const data = localStorage.getItem("checkoutItems");
if (data) {
setItems(JSON.parse(data));
}
}, []);

const total = items.reduce(
(sum, item) => sum + Number(item.lprice) * item.quantity,
0
);

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>
<h1 className="text-2xl font-bold mb-4">결제가 완료되었습니다!</h1>

{/* 3.1. 결제 목록 렌더링 */}
<ul className="space-y-4 mb-6">
{items.map((item) => (
<li key={item.productId} className="border-b pb-2">
<p dangerouslySetInnerHTML={{ __html: item.title }}></p>
<p className="text-sm text-gray-600">
수량: {item.quantity}개 / 개당 {Number(item.lprice).toLocaleString()}원
</p>
<p className="font-bold">
소계: {(Number(item.lprice) * item.quantity).toLocaleString()}원
</p>
</li>
))}
</ul>

<div className="text-right font-bold text-lg mb-6">
총 합계: {total.toLocaleString()}원
</div>

{/* 3.2. 홈으로 가기 버튼 구현 */}
<div className="text-center">
<button
onClick={() => router.push("/search")}
className="px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600"
>
홈으로 가기
</button>
</div>
</div>
);
}
6 changes: 5 additions & 1 deletion src/app/layout.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import type { Metadata } from "next";
import { Geist, Geist_Mono } from "next/font/google";
import "./globals.css";
import { UserProvider } from "@/context/UserContext";

const geistSans = Geist({
variable: "--font-geist-sans",
Expand All @@ -27,7 +28,10 @@ export default function RootLayout({
<body
className={`${geistSans.variable} ${geistMono.variable} antialiased`}
>
{children}
{/* childeren을 감싸줌 */}
<UserProvider>
{children}
</UserProvider>
</body>
</html>
);
Expand Down
28 changes: 21 additions & 7 deletions src/app/mypage/page.tsx
Original file line number Diff line number Diff line change
@@ -1,14 +1,28 @@
// 과제 1: 마이페이지 구현
"use client";

import { useUser } from "@/context/UserContext";
import Link from "next/link";
import Header from "@/components/layout/Header"; // 이미 있는 컴포넌트일 경우

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>
{/* Mypage 정보를 UserContext 활용하여 표시 (이름, 아이디, 나이, 핸드폰번호 모두 포함) */}
<div className="flex flex-col items-center min-h-screen bg-gray-50 p-8 space-y-4">
{/* Header 재사용 */}
<Header title="마이페이지" />

{/* 유저 정보 출력 */}
<div className="bg-white shadow-md rounded p-6 w-full max-w-md text-left">
<p className="mb-2"><strong>아이디:</strong> {user.userId}</p>
<p className="mb-2"><strong>나이:</strong> {user.age}</p>
<p className="mb-2"><strong>전화번호:</strong> {user.phoneNumber}</p>
</div>

{/* 1.3. 홈으로 가기 버튼 구현(Link or Router 활용) */}
{/* 홈으로 가기 버튼 */}
<Link href="/serch" className="text-blue-600 hover:underline mt-4">
홈으로 가기
</Link>
</div>
);
}
23 changes: 20 additions & 3 deletions src/app/search/page.tsx
Original file line number Diff line number Diff line change
@@ -1,29 +1,46 @@
"use client";

import { useEffect, useState } from "react";
import Header from "../../component/layout/Header";
import Footer from "../../component/layout/Footer";
import SearchInput from "../../component/search/SearchInput";
import ProductCart from "../../component/shopping/ProductCart";
import CartList from "../../components/shopping/CartList";
import { useUser } from "../../context/UserContext";
import { useEffect } 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 }>({});

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

const handleRemoveFromCart = (id: string) => {
const newCart = Object.fromEntries(
Object.entries(cart).filter(([key]) => key !== id)
);
setCart(newCart);
};

return (
<div className="flex justify-center">
<div className="w-[80%]">
<Header title={`${user.name} 쇼핑`} />
<Header title={`${user.userId} 쇼핑`} />
<SearchInput />
<ProductCart items={result} />

{/* 장바구니 표시 */}
<CartList
cart={cart}
products={result}
onRemove={handleRemoveFromCart}
/>
</div>
</div>
);
Expand Down
14 changes: 12 additions & 2 deletions src/component/search/SearchInput.tsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,18 @@
"use client";
import { useSearch } from "@/context/SearchContext";
import { useEffect, useRef } from "react";

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

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

const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
setQuery(e.target.value);
};

// 검색 기능
const search = async () => {
Expand All @@ -18,14 +28,14 @@ export default function SearchInput() {
}
};

// 2.2. SearchInput 컴포넌트가 최초 렌더링 될 때, input tag에 포커스 되는 기능
const handleInputChange = () => {};


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

return (
<div className="flex justify-center items-center gap-2 mt-4">
<input
ref={inputRef}
type="text"
value={query}
onChange={handleInputChange}
Expand Down
14 changes: 13 additions & 1 deletion src/component/shopping/CartList.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
"use client";
import { useRouter } from "next/navigation";
import { ProductItem } from "@/types/Product";

interface Props {
Expand All @@ -8,6 +9,7 @@ interface Props {
}

export default function CartList({ cart, products, onRemove }: Props) {
const router = useRouter();
const cartItems = Object.entries(cart)
.map(([id, quantity]) => {
const product = products.find((p) => p.productId === id);
Expand All @@ -21,7 +23,17 @@ export default function CartList({ cart, products, onRemove }: Props) {
);

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

localStorage.setItem("checkoutItems", JSON.stringify(checkoutItems));
router.push("/checkout");
};

return (
<div className="p-4 bg-white rounded shadow mt-6">
Expand Down
16 changes: 12 additions & 4 deletions src/component/shopping/ProductCart.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,16 +12,24 @@ export default function ProductCart({ items }: { items: ProductItem[] }) {
const handleAddToCart = (item: ProductItem, quantity: number) => {
setCart((prev) => ({
...prev,
[item.productId]: quantity,
[item.productId]: (prev[item.productId] || 0) + quantity,
}));

localStorage.setItem(item.productId, quantity + "");
localStorage.getItem(item.productId);
// localStorage.setItem(item.productId, quantity + "");
// localStorage.getItem(item.productId);
};

/* 과제 2-3: Cart 아이템 지우기 */
const handleRemoveFromCart = () => {};
const handleRemoveFromCart = (productId: string) => {
const newCart = { ...cart };
delete newCart[productId];
setCart(newCart);
};

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

return (
<div className="p-10">
{/* 상품 리스트 */}
Expand Down
8 changes: 5 additions & 3 deletions src/context/UserContext.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,9 @@ import { createContext, ReactNode, useContext, useState } from "react";

// User
interface User {
name: string;
userId: string;
age: number;
phoneNumber: string;
// age: number
// 추가하고 싶은 속성들 ...
}
Expand All @@ -22,7 +24,7 @@ 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>({ userId: "202302561", age: 22, phoneNumber: "010-1234-5678" });
return (
<UserContext.Provider value={{ user, setUser }}>
{children}
Expand All @@ -35,7 +37,7 @@ export const useUser = () => {
const context = useContext(UserContext);
// 에러처리
if (!context) {
throw new Error("error");
throw new Error("useUser must be used within a UserProvider");
}
return context;
};