SurfSense/surfsense_web/lib/electric/context.ts
Anish Sarkar 703ec08d19 feat: Reduce memory footprint for PGlite, Implement user-specific Electric SQL database management
- Added cleanup logic for other users' databases on login to ensure data isolation.
- Introduced best-effort cleanup on logout to remove stale databases.
- Updated Electric client initialization to support user-specific databases.
- Refactored hooks to utilize the Electric context for better state management and prevent race conditions.
- Enhanced error handling and logging for Electric SQL operations.
2026-01-15 15:22:23 +05:30

37 lines
1 KiB
TypeScript

"use client";
import { createContext, useContext } from "react";
import type { ElectricClient } from "./client";
/**
* Context for sharing the Electric SQL client across the app
*
* This ensures:
* 1. Single initialization point (ElectricProvider only)
* 2. No race conditions (hooks wait for context)
* 3. Clean cleanup (ElectricProvider manages lifecycle)
*/
export const ElectricContext = createContext<ElectricClient | null>(null);
/**
* Hook to get the Electric client from context
* Returns null if Electric is not initialized yet
*/
export function useElectricClient(): ElectricClient | null {
return useContext(ElectricContext);
}
/**
* Hook to get the Electric client, throwing if not available
* Use this when you're sure Electric should be initialized
*/
export function useElectricClientOrThrow(): ElectricClient {
const client = useContext(ElectricContext);
if (!client) {
throw new Error(
"Electric client not available. Make sure you're inside ElectricProvider and user is authenticated."
);
}
return client;
}