2026-01-12 12:47:00 +05:30
|
|
|
"use client"
|
|
|
|
|
|
|
|
|
|
import { useEffect, useState } from 'react'
|
2026-01-12 14:53:18 +05:30
|
|
|
import { initElectric, isElectricInitialized } from '@/lib/electric/client'
|
2026-01-12 12:47:00 +05:30
|
|
|
|
|
|
|
|
interface ElectricProviderProps {
|
|
|
|
|
children: React.ReactNode
|
|
|
|
|
}
|
|
|
|
|
|
2026-01-12 14:53:18 +05:30
|
|
|
/**
|
|
|
|
|
* ElectricProvider initializes the Electric SQL client with PGlite
|
|
|
|
|
*
|
|
|
|
|
* This provider ensures Electric is initialized before rendering children,
|
|
|
|
|
* but doesn't block if initialization fails (app can still work without real-time sync)
|
|
|
|
|
*/
|
2026-01-12 12:47:00 +05:30
|
|
|
export function ElectricProvider({ children }: ElectricProviderProps) {
|
|
|
|
|
const [initialized, setInitialized] = useState(false)
|
|
|
|
|
const [error, setError] = useState<Error | null>(null)
|
|
|
|
|
|
|
|
|
|
useEffect(() => {
|
2026-01-12 14:53:18 +05:30
|
|
|
// Skip if already initialized
|
|
|
|
|
if (isElectricInitialized()) {
|
|
|
|
|
setInitialized(true)
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
let mounted = true
|
|
|
|
|
|
2026-01-12 12:47:00 +05:30
|
|
|
async function init() {
|
|
|
|
|
try {
|
|
|
|
|
await initElectric()
|
2026-01-12 14:53:18 +05:30
|
|
|
if (mounted) {
|
|
|
|
|
setInitialized(true)
|
|
|
|
|
setError(null)
|
|
|
|
|
}
|
2026-01-12 12:47:00 +05:30
|
|
|
} catch (err) {
|
|
|
|
|
console.error('Failed to initialize Electric SQL:', err)
|
2026-01-12 14:53:18 +05:30
|
|
|
if (mounted) {
|
|
|
|
|
setError(err instanceof Error ? err : new Error('Failed to initialize Electric SQL'))
|
|
|
|
|
// Don't block rendering if Electric SQL fails - app can still work
|
|
|
|
|
setInitialized(true)
|
|
|
|
|
}
|
2026-01-12 12:47:00 +05:30
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
init()
|
2026-01-12 14:53:18 +05:30
|
|
|
|
|
|
|
|
return () => {
|
|
|
|
|
mounted = false
|
|
|
|
|
}
|
2026-01-12 12:47:00 +05:30
|
|
|
}, [])
|
|
|
|
|
|
|
|
|
|
// Show loading state only briefly, then render children
|
|
|
|
|
// Electric SQL will sync in the background
|
|
|
|
|
if (!initialized) {
|
|
|
|
|
return (
|
|
|
|
|
<div className="flex items-center justify-center min-h-screen">
|
|
|
|
|
<div className="text-muted-foreground">Initializing...</div>
|
|
|
|
|
</div>
|
|
|
|
|
)
|
|
|
|
|
}
|
|
|
|
|
|
2026-01-12 14:53:18 +05:30
|
|
|
// If there's an error, still render children but log the error
|
|
|
|
|
if (error) {
|
|
|
|
|
console.warn('Electric SQL initialization failed, notifications may not sync:', error.message)
|
|
|
|
|
}
|
|
|
|
|
|
2026-01-12 12:47:00 +05:30
|
|
|
return <>{children}</>
|
|
|
|
|
}
|