Skip to content

⚛️ Workshop 3: Building React Frontend

ใน Workshop นี้เราจะสร้างหน้าเว็บ React เพื่อดึงข้อมูลสินค้าจาก Laravel API (Workshop 1) มาแสดงผล

เป้าหมาย:

  • หน้าแสดงรายการสินค้า (Product List)
  • หน้าเพิ่มสินค้าใหม่ (Create Product Form)

🏁 Step 1: สร้างโปรเจกต์ React

เปิด Terminal (คนละหน้าต่างกับ Laravel) แล้วรัน:

bash
# 1. สร้างโปรเจกต์
npm create vite@latest frontend-shop -- --template react

# 2. เข้าโฟลเดอร์และติดตั้ง
cd frontend-shop
npm install

# 3. รันเซิร์ฟเวอร์
npm run dev

เปิด Browser ไปที่ http://localhost:5173


🔌 Step 2: ตั้งค่า CORS ที่ Laravel (สำคัญ!)

ถ้ายังไม่ได้ทำ: ให้กลับไปที่ฝั่ง Laravel แก้ไขไฟล์ config/cors.php:

php
'allowed_origins' => ['http://localhost:5173'], // หรือ ['*'] เพื่อทดสอบ

และอย่าลืมรัน php artisan config:clear หรือ restart server ฝั่ง Laravel (php artisan serve)


📦 Step 3: สร้าง Component แสดงรายการ

แก้ไข src/App.jsx ลบโค้ดเก่าออก แล้วใส่โค้ดใหม่:

jsx
import { useState, useEffect } from 'react';

function App() {
  const [products, setProducts] = useState([]);

  // ดึงข้อมูลเมื่อเข้าหน้าเว็บ
  useEffect(() => {
    fetch('http://localhost:8000/api/products')
      .then(res => res.json())
      .then(data => setProducts(data))
      .catch(err => console.error("Error:", err));
  }, []);

  return (
    <div style={{ padding: '20px' }}>
      <h1>รายการสินค้า (My Store)</h1>
      
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: '10px' }}>
        {products.map(product => (
          <div key={product.id} style={{ border: '1px solid #ddd', padding: '10px' }}>
            <h2>{product.name}</h2>
            <p>{product.description}</p>
            <p style={{ color: 'green', fontWeight: 'bold' }}>ราคา: {product.price} บาท</p>
          </div>
        ))}
      </div>
    </div>
  );
}

export default App;

📝 Step 4: สร้างฟอร์มเพิ่มสินค้า

เพิ่มฟอร์มเข้าไปใน src/App.jsx (เหนือโค้ดแสดงรายการสินค้า):

jsx
// เพิ่ม State สำหรับฟอร์ม
const [newProduct, setNewProduct] = useState({ name: '', price: '' });

// ฟังก์ชันส่งข้อมูล
const handleSubmit = async (e) => {
  e.preventDefault();
  
  const response = await fetch('http://localhost:8000/api/products', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(newProduct)
  });

  if (response.ok) {
    alert("เพิ่มสินค้าสำเร็จ!");
    // ดึงข้อมูลใหม่
    const addedProduct = await response.json();
    setProducts([...products, addedProduct]); // อัปเดต List ทันที
    setNewProduct({ name: '', price: '' }); // ล้างฟอร์ม
  }
};

ส่วน JSX สำหรับฟอร์ม: (แทรกไว้ใต้ <h1>รายการสินค้า...</h1>)

jsx
<form onSubmit={handleSubmit} style={{ marginBottom: '20px', padding: '10px', background: '#f5f5f5' }}>
  <h3>เพิ่มสินค้าใหม่</h3>
  <input 
    type="text" 
    placeholder="ชื่อสินค้า" 
    value={newProduct.name}
    onChange={e => setNewProduct({...newProduct, name: e.target.value})}
    required
  />
  <input 
    type="number" 
    placeholder="ราคา" 
    value={newProduct.price}
    onChange={e => setNewProduct({...newProduct, price: e.target.value})}
    required
  />
  <button type="submit">บันทึก</button>
</form>

✅ Step 5: ทดสอบการทำงาน

  1. ลองกรอกชื่อและราคาสินค้า แล้วกดปุ่ม "บันทึก"
  2. ข้อมูลควรจะเด้งขึ้นมาในรายการด้านล่างทันที (โดยไม่ต้องรีเฟรชหน้า)
  3. ตรวจสอบใน Database ว่าข้อมูลเข้าจริงไหม