Files
wzdj/components/providers/database-provider.tsx
v0 ecae8fcef8 Add new files
#VERCEL_SKIP

Co-authored-by: undefined <undefined+undefined@users.noreply.github.com>
2026-01-04 05:02:13 +00:00

64 lines
1.8 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"use client"
import { createContext, useContext, useState, useEffect, type ReactNode } from "react"
import Dexie from "dexie"
interface DatabaseContextType {
isReady: boolean
error: Error | null
}
const DatabaseContext = createContext<DatabaseContextType>({
isReady: false,
error: null,
})
export function DatabaseProvider({ children }: { children: ReactNode }) {
const [isReady, setIsReady] = useState(false)
const [error, setError] = useState<Error | null>(null)
useEffect(() => {
const initDatabase = async () => {
try {
// 动态导入数据库模块
const { db } = await import("@/lib/db/schema")
const { seedDatabase } = await import("@/lib/db/seed")
await db.open()
await seedDatabase()
setIsReady(true)
} catch (err) {
console.error("[v0] Database init error:", err)
// 如果IndexedDB不可用仍然允许应用运行
if (err instanceof Dexie.MissingAPIError) {
console.warn("[v0] IndexedDB not available, using fallback")
setIsReady(true)
} else {
setError(err as Error)
// 即使出错也允许应用运行
setIsReady(true)
}
}
}
initDatabase()
}, [])
if (!isReady) {
return (
<div className="min-h-screen bg-background flex items-center justify-center">
<div className="text-center">
<div className="w-8 h-8 border-2 border-cyan-500 border-t-transparent rounded-full animate-spin mx-auto mb-4" />
<p className="text-muted-foreground text-sm">...</p>
</div>
</div>
)
}
return <DatabaseContext.Provider value={{ isReady, error }}>{children}</DatabaseContext.Provider>
}
export function useDatabaseContext() {
return useContext(DatabaseContext)
}