[dyad] wrote 1 file(s)

This commit is contained in:
[dyad] 2025-09-10 13:24:45 +02:00
parent 631ef5649e
commit 97b2a4eb8a

View file

@ -26,7 +26,7 @@ export function useDashboardData() {
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const fetchDashboardStats = useCallback(async () => {
const fetchDashboardStats = useCallback(async (abortSignal: AbortSignal) => {
setLoading(true);
setError(null);
try {
@ -36,6 +36,11 @@ export function useDashboardData() {
await pb.admins.authWithPassword('david@wfsales.co.za', '1234567890');
console.log('Re-authenticated as admin successfully.');
} catch (authError: any) {
// Check if the error is due to abortion
if (authError.name === 'AbortError') {
console.log('Authentication request aborted.');
return;
}
console.error('Failed to re-authenticate as admin:', authError);
setError(`Authentication failed: ${authError.message || authError.toString()}`);
setLoading(false);
@ -46,6 +51,7 @@ export function useDashboardData() {
// Fetch all stock items
const stockRecords = await pb.collection('stock_items').getFullList({
sort: '-created',
signal: abortSignal, // Pass the abort signal
});
let calculatedTotalStockValue = 0;
@ -64,6 +70,7 @@ export function useDashboardData() {
const thirtyDaysAgo = subDays(new Date(), 30).toISOString();
const bookOutRecordsLast30Days = await pb.collection('book_out_records').getFullList({
filter: `date_booked_out >= "${thirtyDaysAgo}"`,
signal: abortSignal, // Pass the abort signal
});
let calculatedStockOutLast30Days = 0;
@ -112,6 +119,7 @@ export function useDashboardData() {
// Process all book out records for 'stockOut'
const allBookOutRecords = await pb.collection('book_out_records').getFullList({
sort: '-created',
signal: abortSignal, // Pass the abort signal
});
allBookOutRecords.forEach((record: any) => {
@ -138,6 +146,11 @@ export function useDashboardData() {
setMonthlyActivityData(sortedMonthlyData);
} catch (err: any) {
// Check if the error is due to abortion, if so, ignore it
if (err.name === 'AbortError') {
console.log('Dashboard data fetch aborted.');
return;
}
console.error("Failed to fetch dashboard data:", err);
setError(`Failed to load dashboard data: ${err.message || err.toString()}`);
setStats({
@ -153,7 +166,12 @@ export function useDashboardData() {
}, []);
useEffect(() => {
fetchDashboardStats();
const abortController = new AbortController();
fetchDashboardStats(abortController.signal);
return () => {
abortController.abort(); // Abort any pending requests on unmount or re-run
};
}, [fetchDashboardStats]);
return { stats, monthlyActivityData, loading, error, refresh: fetchDashboardStats };