Skip to content

Commit 55b5c94

Browse files
committed
refactor(produto): extract product search from homepage to hook.
1 parent b08f748 commit 55b5c94

1 file changed

Lines changed: 55 additions & 0 deletions

File tree

web/src/hooks/api/useProducts.ts

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
import { useEffect, useState } from "react";
2+
3+
type Category = {
4+
id: number;
5+
name: string;
6+
};
7+
8+
type Product = {
9+
id: number;
10+
name: string;
11+
category?: Category;
12+
price: number;
13+
};
14+
15+
export default function Home() {
16+
const [products, setProducts] = useState<Product[]>([]);
17+
const [loading, setLoading] = useState(true);
18+
const [error, setError] = useState<string | null>(null);
19+
20+
useEffect(() => {
21+
async function fetchProducts() {
22+
try {
23+
setLoading(true);
24+
25+
console.log("Buscando produtos...");
26+
27+
const res = await fetch("http://localhost:8081/products");
28+
29+
if (!res.ok) throw new Error("Erro ao buscar produtos");
30+
31+
const data: Product[] = await res.json();
32+
33+
console.log("Produtos recebidos:", data);
34+
35+
setProducts(data);
36+
} catch (err: unknown) {
37+
if (err instanceof Error) {
38+
setError("Não foi possível carregar os produtos");
39+
} else {
40+
setError("Erro desconhecido");
41+
}
42+
} finally {
43+
setLoading(false);
44+
}
45+
}
46+
47+
fetchProducts();
48+
}, []);
49+
50+
return {
51+
products,
52+
loading,
53+
error,
54+
};
55+
}

0 commit comments

Comments
 (0)