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 { useEffect, useState } from 'react'
import { apiClient } from '../../services/apiClient'
interface DashboardStats { interface DashboardStats {
totalUsers: number totalUsers: number
@ -20,30 +21,52 @@ export function DashboardHome() {
loadStats() 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 () => { const loadStats = async () => {
setLoading(true) setLoading(true)
try { try {
// Load counts from each endpoint // Load counts from each endpoint
const [users, companies, products, orders] = await Promise.all([ const [users, companies, products, orders] = await Promise.all([
fetch('/api/v1/users?page=1&page_size=1', { apiClient.get('/v1/users?page=1&page_size=1').catch(() => ({ total: 0 })),
headers: { Authorization: `Bearer ${localStorage.getItem('mp-auth-user') ? JSON.parse(localStorage.getItem('mp-auth-user')!).token : ''}` } apiClient.get('/v1/companies').catch(() => ([])),
}).then(r => r.json()).catch(() => ({ total: 0 })), apiClient.get('/v1/products').catch(() => ([])),
fetch('/api/v1/companies?page=1&page_size=1', { apiClient.get('/v1/orders').catch(() => ([]))
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 }))
]) ])
setStats({ setStats({
totalUsers: users.total || 0, totalUsers: extractCount(users),
totalCompanies: companies.total || 0, totalCompanies: extractCount(companies),
totalProducts: products.total || 0, totalProducts: extractCount(products),
totalOrders: orders.total || 0 totalOrders: extractCount(orders)
}) })
} catch (err) { } catch (err) {
console.error('Error loading stats:', err) console.error('Error loading stats:', err)