mirror of
https://github.com/escalante29/WealthySmart.git
synced 2026-07-17 15:28:47 +02:00
Adopt TanStack Query: provider, timeouts, useBudget, Budget page
QueryClientProvider (30s staleTime, 1 retry) + Sonner Toaster at the root. api.ts gains AbortSignal support and a default 30s timeout (FE-24); query cancellation kills the stale-response races (FE-01, FE-03). useBudget is now queries + mutations with targeted ['budget'] invalidation and success/error toasts on every mutation (ARCH-13, UX-01); month navigation keeps the previous month visible while fetching. Budget's transaction list is a cancellable query with placeholder data; deferred-toggle gets feedback (UX-05); both panels render a shared ErrorState with retry instead of failing silently. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
@@ -1,8 +1,7 @@
|
||||
import { useState, useEffect, useCallback } from 'react';
|
||||
import { useState } from 'react';
|
||||
import { useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import { toast } from 'sonner';
|
||||
import {
|
||||
type YearlyProjection,
|
||||
type MonthlyDetail,
|
||||
type RecurringItem,
|
||||
type RecurringItemCreate,
|
||||
type RecurringItemUpdate,
|
||||
getYearlyProjection,
|
||||
@@ -15,89 +14,90 @@ import {
|
||||
deleteBalanceOverride,
|
||||
} from '@/lib/api';
|
||||
|
||||
/** All budget data hangs off the ['budget', ...] key family; every mutation
|
||||
* invalidates the family so projection, month detail and items stay in sync. */
|
||||
export function useBudget(initialYear: number) {
|
||||
const queryClient = useQueryClient();
|
||||
const [year, setYear] = useState(initialYear);
|
||||
const [selectedMonth, setSelectedMonth] = useState<number>(new Date().getMonth() + 1);
|
||||
const [projection, setProjection] = useState<YearlyProjection | null>(null);
|
||||
const [monthDetail, setMonthDetail] = useState<MonthlyDetail | null>(null);
|
||||
const [recurringItems, setRecurringItems] = useState<RecurringItem[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [monthLoading, setMonthLoading] = useState(false);
|
||||
const [selectedMonth, setSelectedMonth] = useState<number>(
|
||||
new Date().getMonth() + 1,
|
||||
);
|
||||
|
||||
const fetchProjection = useCallback(async () => {
|
||||
setLoading(true);
|
||||
const projectionQ = useQuery({
|
||||
queryKey: ['budget', 'projection', year],
|
||||
queryFn: () => getYearlyProjection(year).then((r) => r.data),
|
||||
});
|
||||
|
||||
const monthDetailQ = useQuery({
|
||||
queryKey: ['budget', 'month', year, selectedMonth],
|
||||
queryFn: () => getMonthlyDetail(year, selectedMonth).then((r) => r.data),
|
||||
placeholderData: (prev) => prev, // keep last month visible while navigating
|
||||
});
|
||||
|
||||
const recurringQ = useQuery({
|
||||
queryKey: ['budget', 'recurring'],
|
||||
queryFn: () => getRecurringItems().then((r) => r.data),
|
||||
});
|
||||
|
||||
const invalidate = () =>
|
||||
queryClient.invalidateQueries({ queryKey: ['budget'] });
|
||||
|
||||
async function mutateWithToast(
|
||||
action: () => Promise<unknown>,
|
||||
success: string,
|
||||
failure: string,
|
||||
) {
|
||||
try {
|
||||
const { data } = await getYearlyProjection(year);
|
||||
setProjection(data);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
await action();
|
||||
} catch (err) {
|
||||
toast.error(failure);
|
||||
throw err;
|
||||
}
|
||||
}, [year]);
|
||||
|
||||
const fetchMonthDetail = useCallback(async () => {
|
||||
setMonthLoading(true);
|
||||
try {
|
||||
const { data } = await getMonthlyDetail(year, selectedMonth);
|
||||
setMonthDetail(data);
|
||||
} finally {
|
||||
setMonthLoading(false);
|
||||
}
|
||||
}, [year, selectedMonth]);
|
||||
|
||||
const fetchRecurringItems = useCallback(async () => {
|
||||
const { data } = await getRecurringItems();
|
||||
setRecurringItems(data);
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
fetchProjection();
|
||||
fetchRecurringItems();
|
||||
}, [fetchProjection, fetchRecurringItems]);
|
||||
|
||||
useEffect(() => {
|
||||
fetchMonthDetail();
|
||||
}, [fetchMonthDetail]);
|
||||
|
||||
const addItem = async (data: RecurringItemCreate) => {
|
||||
await createRecurringItem(data);
|
||||
await Promise.all([fetchProjection(), fetchMonthDetail(), fetchRecurringItems()]);
|
||||
};
|
||||
|
||||
const updateItem = async (id: number, data: RecurringItemUpdate) => {
|
||||
await apiUpdateItem(id, data);
|
||||
await Promise.all([fetchProjection(), fetchMonthDetail(), fetchRecurringItems()]);
|
||||
};
|
||||
|
||||
const deleteItem = async (id: number) => {
|
||||
await apiDeleteItem(id);
|
||||
await Promise.all([fetchProjection(), fetchMonthDetail(), fetchRecurringItems()]);
|
||||
};
|
||||
|
||||
const saveBalanceOverride = async (overrideYear: number, month: number, value: number) => {
|
||||
await upsertBalanceOverride(overrideYear, month, value);
|
||||
await fetchProjection();
|
||||
};
|
||||
|
||||
const clearBalanceOverride = async (overrideYear: number, month: number) => {
|
||||
await deleteBalanceOverride(overrideYear, month);
|
||||
await fetchProjection();
|
||||
};
|
||||
toast.success(success);
|
||||
await invalidate();
|
||||
}
|
||||
|
||||
return {
|
||||
year,
|
||||
setYear,
|
||||
selectedMonth,
|
||||
setSelectedMonth,
|
||||
projection,
|
||||
monthDetail,
|
||||
recurringItems,
|
||||
loading,
|
||||
monthLoading,
|
||||
addItem,
|
||||
updateItem,
|
||||
deleteItem,
|
||||
saveBalanceOverride,
|
||||
clearBalanceOverride,
|
||||
refresh: () => Promise.all([fetchProjection(), fetchMonthDetail(), fetchRecurringItems()]),
|
||||
projection: projectionQ.data ?? null,
|
||||
monthDetail: monthDetailQ.data ?? null,
|
||||
recurringItems: recurringQ.data ?? [],
|
||||
loading: projectionQ.isPending,
|
||||
monthLoading: monthDetailQ.isFetching,
|
||||
error: projectionQ.error ?? monthDetailQ.error ?? recurringQ.error ?? null,
|
||||
addItem: (data: RecurringItemCreate) =>
|
||||
mutateWithToast(
|
||||
() => createRecurringItem(data),
|
||||
'Item recurrente creado',
|
||||
'No se pudo crear el item',
|
||||
),
|
||||
updateItem: (id: number, data: RecurringItemUpdate) =>
|
||||
mutateWithToast(
|
||||
() => apiUpdateItem(id, data),
|
||||
'Item recurrente actualizado',
|
||||
'No se pudo actualizar el item',
|
||||
),
|
||||
deleteItem: (id: number) =>
|
||||
mutateWithToast(
|
||||
() => apiDeleteItem(id),
|
||||
'Item recurrente eliminado',
|
||||
'No se pudo eliminar el item',
|
||||
),
|
||||
saveBalanceOverride: (overrideYear: number, month: number, value: number) =>
|
||||
mutateWithToast(
|
||||
() => upsertBalanceOverride(overrideYear, month, value),
|
||||
'Balance ajustado',
|
||||
'No se pudo ajustar el balance',
|
||||
),
|
||||
clearBalanceOverride: (overrideYear: number, month: number) =>
|
||||
mutateWithToast(
|
||||
() => deleteBalanceOverride(overrideYear, month),
|
||||
'Ajuste de balance eliminado',
|
||||
'No se pudo eliminar el ajuste',
|
||||
),
|
||||
refresh: invalidate,
|
||||
};
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user