Skip to content

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

Open
claygeo wants to merge 2 commits intoelectric-sql:mainfrom
claygeo:fix/usepglite-null-outside-provider
Open

fix(react): usePGlite returns null instead of throwing outside provider#953
claygeo wants to merge 2 commits intoelectric-sql:mainfrom
claygeo:fix/usepglite-null-outside-provider

Conversation

@claygeo
Copy link
Copy Markdown

@claygeo claygeo commented Mar 30, 2026

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 added 2 commits March 30, 2026 11:10
Previously calling usePGlite() without a PGliteProvider ancestor threw
a runtime error. This made it impossible to use pglite conditionally
or in components that render before the provider mounts.

Change the hook to return null when no provider is found. The type
signature is updated from T to T | null so TypeScript enforces null
checks at the call site — callers guard with `if (!db) return`.

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

Fixes: electric-sql#878
Since usePGlite now returns null outside a provider instead of throwing,
hooks that call db.live.query() would crash with a TypeError on null
dereference. Add an early return in the useEffect so subscriptions are
simply skipped when no provider is mounted.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

React: Don't throw an error when usePGlite() doesn't find a PGlite instance

1 participant