fix: Add null checks to prevent 'Cannot read properties of null' errors

This commit is contained in:
Usman Baig
2026-01-16 14:23:23 +01:00
parent 0c3fd5f766
commit 8643443300
6 changed files with 12 additions and 11 deletions

View File

@@ -50,12 +50,12 @@ export default function SiteDashboardPage() {
getCountries(siteId, dateRange.start, dateRange.end, 10),
])
setSite(siteData)
setStats(statsData)
setRealtime(realtimeData.visitors)
setDailyStats(dailyData)
setTopPages(pagesData)
setTopReferrers(referrersData)
setCountries(countriesData)
setStats(statsData || { pageviews: 0, visitors: 0 })
setRealtime(realtimeData?.visitors || 0)
setDailyStats(Array.isArray(dailyData) ? dailyData : [])
setTopPages(Array.isArray(pagesData) ? pagesData : [])
setTopReferrers(Array.isArray(referrersData) ? referrersData : [])
setCountries(Array.isArray(countriesData) ? countriesData : [])
} catch (error: any) {
toast.error('Failed to load data: ' + (error.message || 'Unknown error'))
} finally {

View File

@@ -7,7 +7,7 @@ interface CountriesProps {
}
export default function Countries({ countries }: CountriesProps) {
if (countries.length === 0) {
if (!countries || countries.length === 0) {
return (
<div className="bg-white dark:bg-neutral-900 border border-neutral-200 dark:border-neutral-800 rounded-xl p-6">
<h3 className="text-lg font-semibold mb-4 text-neutral-900 dark:text-white">

View File

@@ -7,7 +7,7 @@ interface TopPagesProps {
}
export default function TopPages({ pages }: TopPagesProps) {
if (pages.length === 0) {
if (!pages || pages.length === 0) {
return (
<div className="bg-white dark:bg-neutral-900 border border-neutral-200 dark:border-neutral-800 rounded-xl p-6">
<h3 className="text-lg font-semibold mb-4 text-neutral-900 dark:text-white">

View File

@@ -7,7 +7,7 @@ interface TopReferrersProps {
}
export default function TopReferrers({ referrers }: TopReferrersProps) {
if (referrers.length === 0) {
if (!referrers || referrers.length === 0) {
return (
<div className="bg-white dark:bg-neutral-900 border border-neutral-200 dark:border-neutral-800 rounded-xl p-6">
<h3 className="text-lg font-semibold mb-4 text-neutral-900 dark:text-white">

View File

@@ -19,9 +19,10 @@ export default function SiteList() {
try {
setLoading(true)
const data = await listSites()
setSites(data)
setSites(Array.isArray(data) ? data : [])
} catch (error: any) {
toast.error('Failed to load sites: ' + (error.message || 'Unknown error'))
setSites([]) // Ensure sites is always an array
} finally {
setLoading(false)
}

View File

@@ -20,7 +20,7 @@ export interface UpdateSiteRequest {
export async function listSites(): Promise<Site[]> {
const response = await apiRequest<{ sites: Site[] }>('/sites')
return response.sites
return response?.sites || []
}
export async function getSite(id: string): Promise<Site> {