1import { useEffect, useState } from 'react';
2
3type Product = {
4 id: string;
5 name: string;
6 stock: number;
7};
8
9export function useProducts(category: string) {
10 const [items, setItems] = useState<Product[]>([]);
11 const [loading, setLoading] = useState(true);
12
13 useEffect(() => {
14 const controller = new AbortController();
15
16 fetch(`/api/products?category=${category}`, {
17 signal: controller.signal,
18 })
19 .then((res) => res.json())
20 .then((data: Product[]) => setItems(data))
21 .finally(() => setLoading(false));
22
23 return () => controller.abort();
24 }, [category]);
25
26 return { items, loading };
27}
28
29export function ProductGrid({ category }: { category: string }) {
30 const { items, loading } = useProducts(category);
31
32 if (loading) return <Spinner />;
33
34 return (
35 <ul className="grid grid-cols-3 gap-6">
36 {items.map((item) => (
37 <li key={item.id}>
38 <h3>{item.name}</h3>
39 <p>{item.stock > 0 ? 'Disponible' : 'Agotado'}</p>
40 </li>
41 ))}
42 </ul>
43 );
44}
45
46export async function GET(request: Request) {
47 const { searchParams } = new URL(request.url);
48 const category = searchParams.get('category');
49
50 const rows = await db.product.findMany({
51 where: { category },
52 orderBy: { name: 'asc' },
53 });
54
55 return Response.json(rows);
56}
57
1import { useEffect, useState } from 'react';
2
3type Product = {
4 id: string;
5 name: string;
6 stock: number;
7};
8
9export function useProducts(category: string) {
10 const [items, setItems] = useState<Product[]>([]);
11 const [loading, setLoading] = useState(true);
12
13 useEffect(() => {
14 const controller = new AbortController();
15
16 fetch(`/api/products?category=${category}`, {
17 signal: controller.signal,
18 })
19 .then((res) => res.json())
20 .then((data: Product[]) => setItems(data))
21 .finally(() => setLoading(false));
22
23 return () => controller.abort();
24 }, [category]);
25
26 return { items, loading };
27}
28
29export function ProductGrid({ category }: { category: string }) {
30 const { items, loading } = useProducts(category);
31
32 if (loading) return <Spinner />;
33
34 return (
35 <ul className="grid grid-cols-3 gap-6">
36 {items.map((item) => (
37 <li key={item.id}>
38 <h3>{item.name}</h3>
39 <p>{item.stock > 0 ? 'Disponible' : 'Agotado'}</p>
40 </li>
41 ))}
42 </ul>
43 );
44}
45
46export async function GET(request: Request) {
47 const { searchParams } = new URL(request.url);
48 const category = searchParams.get('category');
49
50 const rows = await db.product.findMany({
51 where: { category },
52 orderBy: { name: 'asc' },
53 });
54
55 return Response.json(rows);
56}
57