Update src/hooks/useProduct.ts

This commit is contained in:
2026-03-11 18:36:22 +00:00
parent 21d44b3def
commit 8250ee1c9c

View File

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