Fix admin dashboard stats loading

This commit is contained in:
Tiago Yamamoto 2025-12-22 11:21:56 -03:00
parent 03a14b628b
commit c288767057

View file

@ -1,4 +1,5 @@
import { useEffect, useState } from 'react'
import { apiClient } from '../../services/apiClient'
interface DashboardStats {
totalUsers: number
@ -20,30 +21,52 @@ export function DashboardHome() {
loadStats()
}, [])
const extractCount = (payload: unknown): number => {
if (Array.isArray(payload)) {
return payload.length
}
if (payload && typeof payload === 'object') {
const record = payload as Record<string, unknown>
if (typeof record.total === 'number') {
return record.total
}
const possibleCollections = [
record.items,
record.users,
record.companies,
record.products,
record.orders
]
for (const collection of possibleCollections) {
if (Array.isArray(collection)) {
return collection.length
}
}
}
return 0
}
const loadStats = async () => {
setLoading(true)
try {
// Load counts from each endpoint
const [users, companies, products, orders] = await Promise.all([
fetch('/api/v1/users?page=1&page_size=1', {
headers: { Authorization: `Bearer ${localStorage.getItem('mp-auth-user') ? JSON.parse(localStorage.getItem('mp-auth-user')!).token : ''}` }
}).then(r => r.json()).catch(() => ({ total: 0 })),
fetch('/api/v1/companies?page=1&page_size=1', {
headers: { Authorization: `Bearer ${localStorage.getItem('mp-auth-user') ? JSON.parse(localStorage.getItem('mp-auth-user')!).token : ''}` }
}).then(r => r.json()).catch(() => ({ total: 0 })),
fetch('/api/v1/products?page=1&page_size=1', {
headers: { Authorization: `Bearer ${localStorage.getItem('mp-auth-user') ? JSON.parse(localStorage.getItem('mp-auth-user')!).token : ''}` }
}).then(r => r.json()).catch(() => ({ total: 0 })),
fetch('/api/v1/orders?page=1&page_size=1', {
headers: { Authorization: `Bearer ${localStorage.getItem('mp-auth-user') ? JSON.parse(localStorage.getItem('mp-auth-user')!).token : ''}` }
}).then(r => r.json()).catch(() => ({ total: 0 }))
apiClient.get('/v1/users?page=1&page_size=1').catch(() => ({ total: 0 })),
apiClient.get('/v1/companies').catch(() => ([])),
apiClient.get('/v1/products').catch(() => ([])),
apiClient.get('/v1/orders').catch(() => ([]))
])
setStats({
totalUsers: users.total || 0,
totalCompanies: companies.total || 0,
totalProducts: products.total || 0,
totalOrders: orders.total || 0
totalUsers: extractCount(users),
totalCompanies: extractCount(companies),
totalProducts: extractCount(products),
totalOrders: extractCount(orders)
})
} catch (err) {
console.error('Error loading stats:', err)