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.

42 changes: 39 additions & 3 deletions src/app/checkout/page.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
// CheckoutPage
import { useState } from "react";

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

interface CheckoutItem {
product: ProductItem;
Expand All @@ -9,13 +10,48 @@ interface CheckoutItem {
// 과제 3
export default function CheckoutPage() {
const [items, setItems] = useState<CheckoutItem[]>([]);
const router = useRouter();

useEffect(() => {
const data = localStorage.getItem("checkoutItems");
if (data) {
const parsed = JSON.parse(data) as CheckoutItem[];
setItems(parsed);
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. 결제하기 구현 */}
{items.length > 0 ? (
<>
<ul className="divide-y">
{items.map((item, index) => (
<li key={index} className="py-4 flex justify-between">
<span>{item.product.mallName} (x{item.quantity})</span>
<span>{Number(item.product.lprice).toLocaleString()}원</span>
</li>
))}
<li className="py-4 font-bold flex justify-between">
<span>총 결제 금액</span>
<span>{total.toLocaleString()}원</span>
</li>
</ul>
</>
)
:
<div className="text-center text-gray-500">장바구니에 상품이 없습니다.</div>
}
<div></div>
{/* 3.2. 홈으로 가기 버튼 구현 */}
<button onClick={() => router.push("/")} className="mt-6 w-full bg-blue-500 text-white py-2 rounded hover:bg-blue-600 transition">
홈으로 가기
</button>
</div>
);
}
}
3 changes: 2 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,7 @@ export default function RootLayout({
<body
className={`${geistSans.variable} ${geistMono.variable} antialiased`}
>
{children}
<UserProvider>{children}</UserProvider>
</body>
</html>
);
Expand Down
36 changes: 33 additions & 3 deletions src/app/mypage/page.tsx
Original file line number Diff line number Diff line change
@@ -1,14 +1,44 @@
// 과제 1: 마이페이지 구현
"use client";

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

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="마이페이지" />
<div className="max-w-3xl w-full p-6 bg-white rounded shadow mt-6">
<h1 className="text-2xl font-bold mb-4">마이페이지</h1>
<div className="space-y-4">
<div>
<strong>이름:</strong> {user.name}
</div>
<div>
<strong>아이디:</strong> {user.userId}
</div>
<div>
<strong>나이:</strong> {user.age}세
</div>
<div>
<strong>핸드폰번호:</strong> {user.phoneNumber}
</div>
<div>
<strong>이메일:</strong> {user.email}
</div>
</div>
</div>
{/* Mypage 정보를 UserContext 활용하여 표시 (이름, 아이디, 나이, 핸드폰번호 모두 포함) */}

{/* 1.3. 홈으로 가기 버튼 구현(Link or Router 활용) */}
<Link href="/" className="mt-6 w-full max-w-xs bg-blue-500 text-white py-2 rounded hover:bg-blue-600 transition">
홈으로 가기
</Link>
</div>
);
}
}
11 changes: 9 additions & 2 deletions src/app/search/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,13 +12,20 @@ export default function SearchHome() {
const { user, setUser } = useUser();
const { result } = useSearch();

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

return (
return (
<div className="flex justify-center">
<div className="w-[80%]">
<Header title={`${user.name} 쇼핑`} />
Expand Down
11 changes: 10 additions & 1 deletion src/component/search/SearchInput.tsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,14 @@
"use client";
import { useSearch } from "@/context/SearchContext";
import React, { useEffect, useRef } from "react";

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

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

// 검색 기능
const search = async () => {
Expand All @@ -19,13 +25,16 @@ 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)

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

interface Props {
cart: { [productId: string]: number };
Expand All @@ -19,9 +20,23 @@ export default function CartList({ cart, products, onRemove }: Props) {
(sum, item) => sum + Number(item.lprice) * item.quantity,
0
);
const router = useRouter();

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

localStorage.setItem("checkoutItems", JSON.stringify(checkoutItems));

router.push("/checkout");
};

return (
<div className="p-4 bg-white rounded shadow mt-6">
Expand Down
25 changes: 23 additions & 2 deletions src/component/shopping/ProductCart.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,12 @@ export default function ProductCart({ items }: { items: ProductItem[] }) {
const [cart, setCart] = useState<{ [id: string]: number }>({}); // {"88159814281" : 1}
const [showCart, setShowCart] = useState(false); // 과제 2.1

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


// 카트에 담기
const handleAddToCart = (item: ProductItem, quantity: number) => {
setCart((prev) => ({
Expand All @@ -20,15 +26,30 @@ export default function ProductCart({ items }: { items: ProductItem[] }) {
};

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

localStorage.removeItem(productId);
};

return (
<div className="p-10">
{/* 상품 리스트 */}
<ProductList items={items} onAddToCart={handleAddToCart} />
{/* 장바구니 */}
{/* 2.1. 조건부 카트 보이기: 카트에 담긴 상품이 없으면 카트가 보이지 않고, 카트에 담긴 물건이 있으면 카트가 보인다 */}
<CartList cart={cart} products={items} onRemove={handleRemoveFromCart} />
{showCart && (
<CartList
cart={cart}
products={items}
onRemove={handleRemoveFromCart}
/>
)}
</div>
);
}
25 changes: 13 additions & 12 deletions src/context/UserContext.tsx
Original file line number Diff line number Diff line change
@@ -1,41 +1,42 @@
"use client";
import { createContext, ReactNode, useContext, useState } from "react";

// 과제 1.1 UserContext 구현

// User
// User 타입 정의
interface User {
name: string;
// age: number
// 추가하고 싶은 속성들 ...
userId: string;
age: number;
phoneNumber: string;
}
// UserContextType

interface UserContextType {
user: User;
setUser: (user: User) => void;
}

// 1. createContext
export const UserContext = createContext<UserContextType | undefined>(
undefined
);

// 2. Provider 생성
export const UserProvider = ({ children }: { children: ReactNode }) => {
const [user, setUser] = useState<User>({ name: "" });
const [user, setUser] = useState<User>({
name: "정재현",
userId: "mhgrid",
age: 26,
phoneNumber: "010-1234-5678",
});

return (
<UserContext.Provider value={{ user, setUser }}>
{children}
</UserContext.Provider>
);
};

// 3. user 정보를 사용하기 위한 custom hook
export const useUser = () => {
const context = useContext(UserContext);
// 에러처리
if (!context) {
throw new Error("error");
throw new Error("UserContext 내부에서만 사용해야 합니다.");
}
return context;
};
2 changes: 1 addition & 1 deletion tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
"moduleResolution": "bundler",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve",
"jsx": "react-jsx",
"incremental": true,
"plugins": [
{
Expand Down