Files
ballistic-builder/pages/builder.js

87 lines
3.1 KiB
JavaScript
Raw Normal View History

2024-11-20 13:49:58 -05:00
import { useState, useEffect } from "react";
2024-11-20 12:52:44 -05:00
export default function Builder() {
2024-11-20 13:49:58 -05:00
const [products, setProducts] = useState([]); // Available products from the API
const [build, setBuild] = useState([]); // User's selected parts
const [loading, setLoading] = useState(true);
2024-11-20 12:52:44 -05:00
2024-11-20 13:49:58 -05:00
// Fetch available products on page load
useEffect(() => {
async function fetchProducts() {
try {
const response = await fetch("/api/products"); // Replace with your actual API endpoint
const data = await response.json();
setProducts(data);
setLoading(false);
} catch (error) {
console.error("Error fetching products:", error);
setLoading(false);
}
2024-11-20 12:52:44 -05:00
}
2024-11-20 13:49:58 -05:00
fetchProducts();
}, []);
// Add a product to the build
const addToBuild = (product) => {
setBuild((prevBuild) => [...prevBuild, product]);
2024-11-20 12:52:44 -05:00
};
2024-11-20 13:49:58 -05:00
// Remove a product from the build
const removeFromBuild = (productId) => {
setBuild((prevBuild) => prevBuild.filter((item) => item.id !== productId));
2024-11-20 12:52:44 -05:00
};
return (
<div className="bg-gray-100 min-h-screen p-6">
2024-11-20 13:49:58 -05:00
<div className="max-w-5xl mx-auto">
2024-11-20 12:52:44 -05:00
<h1 className="text-3xl font-bold text-center mb-6">Build Your Firearm</h1>
2024-11-20 13:49:58 -05:00
{/* Available Products */}
<div className="bg-white shadow-md rounded p-6 mb-6">
<h2 className="text-xl font-bold mb-4">Available Products</h2>
{loading ? (
<p className="text-gray-700">Loading products...</p>
) : (
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
{products.map((product) => (
<div key={product.id} className="bg-gray-100 shadow rounded p-4">
<h3 className="text-lg font-bold">{product.name}</h3>
<p className="text-gray-700">{product.description}</p>
<p className="text-gray-900 font-bold">${product.price}</p>
<button
className="bg-blue-500 text-white px-4 py-2 rounded mt-4 hover:bg-blue-700"
onClick={() => addToBuild(product)}
>
Add to Build
</button>
</div>
))}
</div>
)}
</div>
{/* Current Build */}
2024-11-20 12:52:44 -05:00
<div className="bg-white shadow-md rounded p-6">
2024-11-20 13:49:58 -05:00
<h2 className="text-xl font-bold mb-4">Current Build</h2>
{build.length === 0 ? (
<p className="text-gray-700">No parts added yet. Start building your firearm!</p>
) : (
<ul className="list-disc list-inside">
{build.map((item) => (
<li key={item.id} className="flex justify-between items-center">
<span>{item.name}</span>
<button
className="text-red-500 hover:underline"
onClick={() => removeFromBuild(item.id)}
>
Remove
</button>
</li>
))}
</ul>
)}
2024-11-20 12:52:44 -05:00
</div>
</div>
</div>
);
}