File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments