Update src/hooks/useProduct.ts

This commit is contained in:
2026-03-08 22:21:18 +00:00
parent 61fd21c259
commit 82b0c18e52

View File

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