Skip to main content

Dashboard & Analytics Hooks

Hooks for fetching user dashboard statistics, geographic analytics data, and application version information.

useDashboardStats

Fetches comprehensive user dashboard statistics including submissions, views, engagement, and chart data from the client dashboard API.

useDashboardStats(): UseQueryResult<UserStats>

UserStats Shape

FieldTypeDescription
totalSubmissionsnumberTotal items submitted by the user
totalViewsnumberTotal views across all user items
totalVotesReceivednumberTotal votes received
totalCommentsReceivednumberTotal comments received
viewsAvailablebooleanWhether view tracking is enabled
recentActivityobject{ newSubmissions, newViews } for recent period
uniqueItemsInteractednumberItems the user has interacted with
totalActivitynumberOverall activity count

Chart Data Fields

FieldTypeDescription
activityChartDataActivityData[]Daily activity (submissions, views, engagement)
engagementChartData{ name, value, color }[]Engagement breakdown for pie/donut charts
submissionTimelineSubmissionTimelineData[]Monthly submission counts
engagementOverviewEngagementOverviewData[]Weekly votes and comments
statusBreakdownStatusBreakdownData[]Approved/Pending/Rejected distribution
topItemsTopItem[]Best performing items (views, votes, comments)
periodComparisonPeriodComparisonDataExportCurrent vs previous period metrics
categoryPerformanceCategoryPerformanceDataExport[]Performance by category
approvalTrendApprovalTrendDataExport[]Approval rates over time
submissionCalendarSubmissionCalendarDataExport[]Calendar heatmap data
engagementDistributionEngagementDistributionData[]Engagement distribution data

Query Configuration

SettingValue
Query key['dashboard-stats']
Stale time5 minutes
EndpointGET /api/client/dashboard/stats
import { useDashboardStats } from '@/hooks/use-dashboard-stats';

function Dashboard() {
const { data: stats, isLoading } = useDashboardStats();

if (isLoading) return <DashboardSkeleton />;

return (
<div>
<StatCard title="Submissions" value={stats.totalSubmissions} />
<StatCard title="Views" value={stats.totalViews} />
<StatCard title="Votes" value={stats.totalVotesReceived} />
<ActivityChart data={stats.activityChartData} />
<StatusPieChart data={stats.statusBreakdown} />
</div>
);
}

useGeoAnalytics

Fetches geographic analytics data for the admin dashboard, including location distributions, heatmap data, and index health statistics.

useGeoAnalytics(): UseQueryResult<GeoAnalyticsData>

GeoAnalyticsData Shape

FieldTypeDescription
statsGeoAnalyticsStatsAggregate location statistics
distributionsobjectDistribution breakdowns
locationsGeoLocation[]Individual item locations
heatmapDataHeatmapPoint[]Points for map heatmap rendering

GeoAnalyticsStats

FieldTypeDescription
totalIndexednumberTotal items in the location index
totalItemsnumberTotal items in the system
itemsWithLocationnumberItems that have location data
itemsRemotenumberItems marked as remote
coveragePercentnumberPercentage of items with location
citiesCountnumberNumber of unique cities
countriesCountnumberNumber of unique countries
indexHealthIndexHealthSync status between index and items
lastIndexedAtstring | nullLast index update timestamp
lastRebuildAtstring | nullLast full rebuild timestamp

Distributions

FieldTypeDescription
distributions.byCountryCountryDistribution[]{ name, count } per country
distributions.byCityCityDistribution[]{ name, count } per city
distributions.byServiceAreaServiceAreaDistribution[]{ area, count } per service area

Query Configuration

SettingValue
Query key['admin-geo-analytics']
Stale time5 minutes
RetryUp to 3 times; skips client errors (status below 500)
EndpointGET /api/admin/geo-analytics
import { useGeoAnalytics } from '@/hooks/use-geo-analytics';

function GeoAnalyticsDashboard() {
const { data, isLoading } = useGeoAnalytics();

if (isLoading) return <Spinner />;

return (
<div>
<StatCard title="Coverage" value={`${data.stats.coveragePercent}%`} />
<StatCard title="Countries" value={data.stats.countriesCount} />
<StatCard title="Cities" value={data.stats.citiesCount} />
<HeatMap data={data.heatmapData} />
<CountryChart data={data.distributions.byCountry} />
</div>
);
}

useLocationIndexAction

Mutation hook for rebuilding or clearing the location index. Automatically invalidates useGeoAnalytics on success.

useLocationIndexAction(): UseMutationResult<Result, Error, 'rebuild' | 'clear'>
ActionResult TypeDescription
'rebuild'RebuildIndexResult{ totalProcessed, indexed, skipped, failed, errors, durationMs }
'clear'ClearIndexResult{ cleared }
const indexAction = useLocationIndexAction();

<button onClick={() => indexAction.mutate('rebuild')}>
Rebuild Index
</button>

useVersionInfo

Fetches application version information with auto-refresh, retry logic, and cache management.

useVersionInfo(options?: UseVersionInfoOptions): UseVersionInfoReturn

Options

OptionTypeDefaultDescription
refreshIntervalnumber300000 (5min)Auto-refresh interval in ms; 0 to disable
retryOnErrorbooleantrueWhether to retry on failures
enabledbooleantrueWhether to enable the query

Return Values

PropertyTypeDescription
versionInfoVersionInfo | nullVersion data (commit, date, author, etc.)
isLoadingbooleanInitial loading state
isErrorbooleanWhether an error occurred
errorUseVersionInfoError | nullError details with optional status code
refetch() => Promise<any>Manual refresh
isStalebooleanWhether the cached data is stale
dataUpdatedAtnumberTimestamp of last successful fetch
invalidateVersionInfo() => Promise<void>Force cache invalidation

Query Configuration

SettingValue
Query key['version-info']
Stale time5 minutes
GC time30 minutes
RetryUp to 2 times; skips 4xx errors
EndpointGET /api/version

Cache utility hook for managing version info across the application:

FunctionDescription
prefetchVersionInfo()Pre-populate the cache
invalidateVersionInfo()Force re-fetch
getVersionInfoFromCache()Read from cache without query
setVersionInfoInCache(data)Manually set cache data
import { useVersionInfo } from '@/hooks/use-version-info';

function VersionBadge() {
const { versionInfo, isLoading } = useVersionInfo({
refreshInterval: 10 * 60 * 1000, // 10 minutes
});

if (isLoading || !versionInfo) return null;

return (
<span title={`${versionInfo.author} - ${versionInfo.date}`}>
{versionInfo.commit.substring(0, 7)}
</span>
);
}

Summary Table

HookPurposeSource File
useDashboardStatsUser dashboard statistics and chartsuse-dashboard-stats.ts
useGeoAnalyticsGeographic analytics for adminuse-geo-analytics.ts
useLocationIndexActionRebuild/clear location indexuse-geo-analytics.ts
useVersionInfoApplication version with auto-refreshuse-version-info.ts
useVersionInfoUtilsVersion cache management utilitiesuse-version-info.ts