fix: handle null API response data to prevent infinite loading

When API returns {"data": null} for empty lists, accessing .plans on
null throws an exception. fetchPlans never reaches setLoading(false),
causing the dashboard to spin forever. Added optional chaining,
fallback defaults, and try-catch-finally to ensure loading stops.

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
Chever John 2026-06-30 02:00:04 +08:00
parent 6b866738be
commit 69543a8aef
No known key found for this signature in database
GPG Key ID: 2894D52ED1211DF0
2 changed files with 18 additions and 13 deletions

View File

@ -47,11 +47,11 @@ export function useDashboardData<T = ProductionPlan | WashingPlan>({
purchaserApi.dashboardStats(),
purchaserApi.listPlans(),
]);
const plans = plansRes.data.plans as unknown as T[];
const plans = (plansRes.data?.plans || []) as unknown as T[];
const stats: DashboardStats = {
all: statsData.total_plans,
producing: statsData.producing_plans,
completed: statsData.completed_plans,
all: statsData.total_plans ?? 0,
producing: statsData.producing_plans ?? 0,
completed: statsData.completed_plans ?? 0,
};
return { plans, stats, rejectedPlanIds: new Set<string>() };
}, []);
@ -61,7 +61,7 @@ export function useDashboardData<T = ProductionPlan | WashingPlan>({
textileApi.dashboardStats(),
textileApi.listPlans(),
]);
const plans = plansRes.data as unknown as T[];
const plans = (plansRes.data || []) as unknown as T[];
const stats: DashboardStats = {
all: statsData.total_plans,
producing: statsData.producing_plans,

View File

@ -87,15 +87,20 @@ export function PurchaserDashboard() {
}, [auth.company, dataLoaded, plans.length]);
const fetchPlans = async () => {
try {
const res = await purchaserApi.listPlans();
const allPlans = res.data.plans;
const allPlans = res.data?.plans || [];
const filteredPlans = allPlans.filter(p =>
!p.process_steps?.some(s => s.status === STEP_STATUS.REJECTED)
);
setPlans(filteredPlans);
} catch (err) {
console.error('Failed to fetch plans:', err);
} finally {
setLoading(false);
setDataLoaded(true);
}
};
// 监听页面可见性变化,返回页面时刷新数据