Update src/hooks/useProduct.ts
This commit is contained in:
@@ -1,45 +1,45 @@
|
||||
"use client";
|
||||
'use client';
|
||||
|
||||
import { useEffect, useState } from "react";
|
||||
import { Product, fetchProduct } from "@/lib/api/product";
|
||||
import { useState, useEffect } from 'react';
|
||||
import { fetchProductById } 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 UseProductState {
|
||||
product: any | null;
|
||||
loading: boolean;
|
||||
error: string | null;
|
||||
}
|
||||
|
||||
export const useProduct = (productId: string) => {
|
||||
const [state, setState] = useState<UseProductState>({
|
||||
product: null,
|
||||
loading: false,
|
||||
error: null,
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (!productId) return;
|
||||
|
||||
const fetchProduct = async () => {
|
||||
setState((prev) => ({ ...prev, loading: true }));
|
||||
try {
|
||||
const product = await fetchProductById(productId);
|
||||
if (!product) throw new Error('Product not found');
|
||||
setState((prev) => ({
|
||||
...prev,
|
||||
loading: false,
|
||||
product,
|
||||
}));
|
||||
} catch (err) {
|
||||
setState((prev) => ({
|
||||
...prev,
|
||||
loading: false,
|
||||
error: err instanceof Error ? err.message : 'Failed to fetch product',
|
||||
}));
|
||||
}
|
||||
};
|
||||
|
||||
fetchProduct();
|
||||
}, [productId]);
|
||||
|
||||
return state;
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user