Press "Enter" to skip to content

Bootsrap giriş dersleri 2

Selahaddin Erdoğan 0
import React, { useReducer, useMemo } from "react";

// ———————————————

// 1. Sabit ürün listesi

// ———————————————

const products = [

  { id: 1, name: "Klavye", price: 450, stock: 5 },

  { id: 2, name: "Mouse", price: 200, stock: 3 },

  { id: 3, name: "Monitör", price: 3200, stock: 0 },

  { id: 4, name: "Kulaklık", price: 650, stock: 8 },

  { id: 5, name: "Webcam", price: 350, stock: 2 },

];

// ———————————————

// 2. Reducer — tüm iş mantığı burada, component’lerde YOK

// ———————————————

function cartReducer(state, action) {

  switch (action.type) {

    case "ADD_ITEM": {

      const product = action.payload;

      const existing = state.find((item) => item.id === product.id);

      if (existing) {

        // Stok sınırını aşma

        if (existing.qty >= product.stock) return state;

        return state.map((item) =>

          item.id === product.id ? { ...item, qty: item.qty + 1 } : item

        );

      }

      if (product.stock === 0) return state;

      return [...state, { ...product, qty: 1 }];

    }

    case "INCREASE": {

      return state.map((item) => {

        if (item.id !== action.payload.id) return item;

        if (item.qty >= item.stock) return item; // stok limiti

        return { ...item, qty: item.qty + 1 };

      });

    }

    case "DECREASE": {

      // Adet 0’a düşerse otomatik kaldır (reducer içinde çözülüyor)

      return state

        .map((item) =>

          item.id === action.payload.id

            ? { ...item, qty: item.qty - 1 }

            : item

        )

        .filter((item) => item.qty > 0);

    }

    case "REMOVE_ITEM": {

      return state.filter((item) => item.id !== action.payload.id);

    }

    default:

      return state;

  }

}

// ———————————————

// 3. Ürün listesi component’i

// ———————————————

function ProductList({ cart, onAdd }) {

  return (

    <div>

      <h2>Ürünler</h2>

      {products.map((product) => {

        const cartItem = cart.find((item) => item.id === product.id);

        const qtyInCart = cartItem ? cartItem.qty : 0;

        const remainingStock = product.stock - qtyInCart;

        const outOfStock = remainingStock <= 0;

        return (

          <div key={product.id} style={{ marginBottom: 8 }}>

            <span>

              {product.name} — {product.price} TL —{" "}

              {remainingStock > 0 ? `Stok: ${remainingStock}` : "Stokta yok"}

            </span>

            <br />

            <button

              disabled={outOfStock}

              onClick={() => onAdd(product)}

              style={{

                border: "1px solid #333",

                borderRadius: 4,

                padding: "4px 10px",

                opacity: outOfStock ? 0.4 : 1,

                cursor: outOfStock ? "not-allowed" : "pointer",

              }}

            >

              {outOfStock ? "Stokta yok" : "Sepete Ekle"}

            </button>

          </div>

        );

      })}

    </div>

  );

}

// ———————————————

// 4. Sepet satırı component’i

// ———————————————

function CartItem({ item, onIncrease, onDecrease, onRemove }) {

  return (

    <div style={{ display: "flex", alignItems: "center", gap: 10, margin: "6px 0" }}>

      <span style={{ minWidth: 80 }}>{item.name}</span>

      <span style={{ border: "1px solid #333", borderRadius: 4, padding: "2px 6px", display: "flex", alignItems: "center", gap: 6 }}>

        <button onClick={() => onDecrease(item.id)}>-</button>

        <span>{item.qty}</span>

        <button onClick={() => onIncrease(item.id)} disabled={item.qty >= item.stock}>

          +

        </button>

      </span>

      <span>{item.price * item.qty} TL</span>

      <button

        onClick={() => onRemove(item.id)}

        style={{ border: "1px solid #333", borderRadius: 4, padding: "4px 10px" }}

      >

        Kaldır

      </button>

    </div>

  );

}

// ———————————————

// 5. Ana Cart bileşeni

// ———————————————

export default function Cart() {

  const [cart, dispatch] = useReducer(cartReducer, []);

  const total = useMemo(

    () => cart.reduce((sum, item) => sum + item.price * item.qty, 0),

    [cart]

  );

  const freeShipping = total >= 1000;

  return (

    <div style={{ padding: 16, fontFamily: "sans-serif" }}>

      <ProductList

        cart={cart}

        onAdd={(product) => dispatch({ type: "ADD_ITEM", payload: product })}

      />

      <h2>Sepet</h2>

      {cart.length === 0 ? (

        <p>Sepet boş</p>

      ) : (

        <>

          {cart.map((item) => (

            <CartItem

              key={item.id}

              item={item}

              onIncrease={(id) =>

                dispatch({ type: "INCREASE", payload: { id } })

              }

              onDecrease={(id) =>

                dispatch({ type: "DECREASE", payload: { id } })

              }

              onRemove={(id) =>

                dispatch({ type: "REMOVE_ITEM", payload: { id } })

              }

            />

          ))}

          <p><strong>Toplam: {total} TL</strong></p>

          {freeShipping && <p>🎉 Kargo bedava!</p>}

        </>

      )}

    </div>

  );

}

Comments are closed.