48 lines
1.4 KiB
TypeScript
48 lines
1.4 KiB
TypeScript
import { useState, useEffect, useCallback } from 'react';
|
|
import { useApi } from './useApi';
|
|
import { useLoader } from '../context/loaders/useLoader';
|
|
import { useToast } from '../context/toasts/useToast';
|
|
|
|
export function useCard(cardId: number) {
|
|
const [card, setCard] = useState<any>(null);
|
|
const [error, setError] = useState<Error | null>(null);
|
|
|
|
const { getCard } = useApi();
|
|
const { withLoader } = useLoader();
|
|
const { addNotification } = useToast();
|
|
|
|
const fetchCard = useCallback(async () => {
|
|
try {
|
|
setError(null);
|
|
const data = await withLoader(() => getCard(cardId), 'Loading card...');
|
|
setCard(data);
|
|
return data;
|
|
} catch (err) {
|
|
const errorMessage = err instanceof Error ? err.message : 'Failed to load card';
|
|
setError(err instanceof Error ? err : new Error(errorMessage));
|
|
addNotification({
|
|
type: 'error',
|
|
title: 'Error Loading Card',
|
|
message: errorMessage,
|
|
duration: 5000,
|
|
});
|
|
return null;
|
|
}
|
|
}, [getCard, cardId, withLoader, addNotification]);
|
|
|
|
const updateCardData = (updatedCard: any) => {
|
|
setCard(updatedCard);
|
|
};
|
|
|
|
useEffect(() => {
|
|
fetchCard();
|
|
}, [cardId, fetchCard]);
|
|
|
|
return {
|
|
card,
|
|
error, // For debugging, not for UI display
|
|
loading: false, // Loading is handled by global loader
|
|
fetchCard,
|
|
updateCardData,
|
|
};
|
|
}
|