Update src/hooks/useProducts.ts

This commit is contained in:
2026-03-08 22:21:19 +00:00
parent 82b0c18e52
commit 184c822595

View File

@@ -1,39 +1,36 @@
"use client";
import { useState, useEffect } from 'react';
import { useEffect, useState } from "react";
import { Product, fetchProducts } from "@/lib/api/product";
interface Product {
id: string;
name: string;
price: string;
imageSrc: string;
}
export function useProducts() {
const [products, setProducts] = useState<Product[]>([]);
const [isLoading, setIsLoading] = useState(true);
const [error, setError] = useState<Error | null>(null);
const [products, setProducts] = useState<Product[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
let isMounted = true;
useEffect(() => {
const fetchProducts = async () => {
try {
setLoading(true);
// Simulate fetch
const response = await fetch('/api/products');
const data = await response.json();
setProducts(data);
setError(null);
} catch (err) {
setError('Failed to fetch products');
setProducts([]);
} finally {
setLoading(false);
}
};
async function loadProducts() {
try {
const data = await fetchProducts();
if (isMounted) {
setProducts(data);
}
} catch (err) {
if (isMounted) {
setError(err instanceof Error ? err : new Error("Failed to fetch products"));
}
} finally {
if (isMounted) {
setIsLoading(false);
}
}
}
fetchProducts();
}, []);
loadProducts();
return () => {
isMounted = false;
};
}, []);
return { products, isLoading, error };
return { products, loading, error };
}