pglite icon indicating copy to clipboard operation
pglite copied to clipboard

fix(react): usePGlite returns null instead of throwing outside provider

Open claygeo opened this issue 8 months ago • 0 comments

Problem

Calling usePGlite() without a <PGliteProvider> ancestor throws a runtime error:

Error: No PGlite instance found, use PGliteProvider to provide one

This makes it impossible to use pglite hooks conditionally or in components that render before the provider mounts — a common pattern for lazy loading, SSR, or optional database features.

Fixes #878

Fix

Return null instead of throwing when no provider is found:

// Before
if (!dbProvided)
  throw new Error('No PGlite instance found, use PGliteProvider to provide one')
return dbProvided

// After
return dbProvided ?? null

The return type is updated from T to T | null, so TypeScript enforces null checks at the call site:

const db = usePGlite()
if (!db) return null  // handles the no-provider case

The explicit-db override path usePGlite(db) is unchanged.

Live query hooks

useLiveQueryImpl in hooks.ts calls db.live.query() unconditionally. With this change, db can be null, so a null guard is added to the useEffect to skip subscriptions when no provider is mounted:

useEffect(() => {
  if (!db) return // no PGliteProvider mounted — skip subscription
  // ...
}, [db, ...])

Tests

Added 3 tests covering: null return outside provider, no-throw outside provider, explicit db arg passthrough.

claygeo avatar Mar 30 '26 15:03 claygeo