chore: ran both frontend and backend linting

This commit is contained in:
Anish Sarkar 2026-01-14 02:05:40 +05:30
parent 99bd2df463
commit 5bd6bd3d67
21 changed files with 861 additions and 739 deletions

View file

@ -1,16 +1,21 @@
"use client"
"use client";
import { useEffect, useState, useCallback, useRef } from 'react'
import { initElectric, isElectricInitialized, type ElectricClient, type SyncHandle } from '@/lib/electric/client'
import type { SearchSourceConnector } from '@/contracts/types/connector.types'
import { useEffect, useState, useCallback, useRef } from "react";
import {
initElectric,
isElectricInitialized,
type ElectricClient,
type SyncHandle,
} from "@/lib/electric/client";
import type { SearchSourceConnector } from "@/contracts/types/connector.types";
export function useConnectorsElectric(searchSpaceId: number | string | null) {
const [electric, setElectric] = useState<ElectricClient | null>(null)
const [connectors, setConnectors] = useState<SearchSourceConnector[]>([])
const [loading, setLoading] = useState(true)
const [error, setError] = useState<Error | null>(null)
const syncHandleRef = useRef<SyncHandle | null>(null)
const liveQueryRef = useRef<{ unsubscribe: () => void } | null>(null)
const [electric, setElectric] = useState<ElectricClient | null>(null);
const [connectors, setConnectors] = useState<SearchSourceConnector[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<Error | null>(null);
const syncHandleRef = useRef<SyncHandle | null>(null);
const liveQueryRef = useRef<{ unsubscribe: () => void } | null>(null);
// Transform connector data from Electric SQL/PGlite to match expected format
// Converts Date objects to ISO strings as expected by Zod schema
@ -18,184 +23,193 @@ export function useConnectorsElectric(searchSpaceId: number | string | null) {
return {
...connector,
last_indexed_at: connector.last_indexed_at
? typeof connector.last_indexed_at === 'string'
? typeof connector.last_indexed_at === "string"
? connector.last_indexed_at
: new Date(connector.last_indexed_at).toISOString()
: null,
next_scheduled_at: connector.next_scheduled_at
? typeof connector.next_scheduled_at === 'string'
? typeof connector.next_scheduled_at === "string"
? connector.next_scheduled_at
: new Date(connector.next_scheduled_at).toISOString()
: null,
created_at: connector.created_at
? typeof connector.created_at === 'string'
? typeof connector.created_at === "string"
? connector.created_at
: new Date(connector.created_at).toISOString()
: new Date().toISOString(), // fallback
}
};
}
// Initialize Electric SQL and start syncing with real-time updates
useEffect(() => {
if (!searchSpaceId) {
setLoading(false)
setConnectors([])
return
setLoading(false);
setConnectors([]);
return;
}
let mounted = true
let mounted = true;
async function init() {
try {
const electricClient = await initElectric()
if (!mounted) return
const electricClient = await initElectric();
if (!mounted) return;
setElectric(electricClient)
setElectric(electricClient);
// Start syncing connectors for this search space via Electric SQL
console.log('Starting Electric SQL sync for connectors, search_space_id:', searchSpaceId)
console.log("Starting Electric SQL sync for connectors, search_space_id:", searchSpaceId);
// Use numeric format for WHERE clause (PGlite sync plugin expects this format)
const handle = await electricClient.syncShape({
table: 'search_source_connectors',
table: "search_source_connectors",
where: `search_space_id = ${searchSpaceId}`,
primaryKey: ['id'],
})
console.log('Electric SQL sync started for connectors:', {
primaryKey: ["id"],
});
console.log("Electric SQL sync started for connectors:", {
isUpToDate: handle.isUpToDate,
hasStream: !!handle.stream,
hasInitialSyncPromise: !!handle.initialSyncPromise,
})
});
// Optimized: Check if already up-to-date before waiting
if (handle.isUpToDate) {
console.log('Connectors sync already up-to-date, skipping wait')
console.log("Connectors sync already up-to-date, skipping wait");
} else if (handle.initialSyncPromise) {
// Only wait if not already up-to-date
console.log('Waiting for initial connectors sync to complete...')
console.log("Waiting for initial connectors sync to complete...");
try {
// Use Promise.race with a shorter timeout to avoid long waits
await Promise.race([
handle.initialSyncPromise,
new Promise(resolve => setTimeout(resolve, 2000)), // Max 2s wait
])
console.log('Initial connectors sync promise resolved or timed out, checking status:', {
new Promise((resolve) => setTimeout(resolve, 2000)), // Max 2s wait
]);
console.log("Initial connectors sync promise resolved or timed out, checking status:", {
isUpToDate: handle.isUpToDate,
})
});
} catch (syncErr) {
console.error('Initial connectors sync failed:', syncErr)
console.error("Initial connectors sync failed:", syncErr);
}
}
// Check status after waiting
console.log('Connectors sync status after waiting:', {
console.log("Connectors sync status after waiting:", {
isUpToDate: handle.isUpToDate,
hasStream: !!handle.stream,
})
});
if (!mounted) {
handle.unsubscribe()
return
handle.unsubscribe();
return;
}
syncHandleRef.current = handle
setLoading(false)
setError(null)
syncHandleRef.current = handle;
setLoading(false);
setError(null);
// Fetch connectors after sync is complete (we already waited above)
await fetchConnectors(electricClient.db)
await fetchConnectors(electricClient.db);
// Set up real-time updates using PGlite live queries
// Electric SQL syncs data to PGlite in real-time via HTTP streaming
// PGlite live queries detect when the synced data changes and trigger callbacks
try {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const db = electricClient.db as any
const db = electricClient.db as any;
// Use PGlite's live query API for real-time updates
// CORRECT API: await db.live.query() then use .subscribe()
if (db.live?.query && typeof db.live.query === 'function') {
if (db.live?.query && typeof db.live.query === "function") {
// IMPORTANT: db.live.query() returns a Promise - must await it!
const liveQuery = await db.live.query(
`SELECT * FROM search_source_connectors WHERE search_space_id = $1 ORDER BY created_at DESC`,
[searchSpaceId]
)
);
if (!mounted) {
liveQuery.unsubscribe?.()
return
liveQuery.unsubscribe?.();
return;
}
// Set initial results immediately from the resolved query
if (liveQuery.initialResults?.rows) {
console.log('📋 Initial live query results for connectors:', liveQuery.initialResults.rows.length)
setConnectors(liveQuery.initialResults.rows.map(transformConnector))
console.log(
"📋 Initial live query results for connectors:",
liveQuery.initialResults.rows.length
);
setConnectors(liveQuery.initialResults.rows.map(transformConnector));
} else if (liveQuery.rows) {
// Some versions have rows directly on the result
console.log('📋 Initial live query results for connectors (direct):', liveQuery.rows.length)
setConnectors(liveQuery.rows.map(transformConnector))
console.log(
"📋 Initial live query results for connectors (direct):",
liveQuery.rows.length
);
setConnectors(liveQuery.rows.map(transformConnector));
}
// Subscribe to changes - this is the correct API!
// The callback fires automatically when Electric SQL syncs new data to PGlite
if (typeof liveQuery.subscribe === 'function') {
if (typeof liveQuery.subscribe === "function") {
liveQuery.subscribe((result: { rows: any[] }) => {
if (mounted && result.rows) {
console.log('🔄 Connectors updated via live query:', result.rows.length)
setConnectors(result.rows.map(transformConnector))
console.log("🔄 Connectors updated via live query:", result.rows.length);
setConnectors(result.rows.map(transformConnector));
}
})
});
// Store unsubscribe function for cleanup
liveQueryRef.current = liveQuery
liveQueryRef.current = liveQuery;
}
} else {
console.warn('PGlite live query API not available, falling back to polling')
console.warn("PGlite live query API not available, falling back to polling");
}
} catch (liveQueryErr) {
console.error('Failed to set up live query for connectors:', liveQueryErr)
console.error("Failed to set up live query for connectors:", liveQueryErr);
// Don't fail completely - we still have the initial fetch
}
} catch (err) {
console.error('Failed to initialize Electric SQL for connectors:', err)
console.error("Failed to initialize Electric SQL for connectors:", err);
if (mounted) {
setError(err instanceof Error ? err : new Error('Failed to initialize Electric SQL for connectors'))
setLoading(false)
setError(
err instanceof Error
? err
: new Error("Failed to initialize Electric SQL for connectors")
);
setLoading(false);
}
}
}
init()
init();
return () => {
mounted = false
syncHandleRef.current?.unsubscribe?.()
liveQueryRef.current?.unsubscribe?.()
syncHandleRef.current = null
liveQueryRef.current = null
}
}, [searchSpaceId])
mounted = false;
syncHandleRef.current?.unsubscribe?.();
liveQueryRef.current?.unsubscribe?.();
syncHandleRef.current = null;
liveQueryRef.current = null;
};
}, [searchSpaceId]);
async function fetchConnectors(db: any) {
try {
const result = await db.query(
`SELECT * FROM search_source_connectors WHERE search_space_id = $1 ORDER BY created_at DESC`,
[searchSpaceId]
)
console.log('📋 Fetched connectors from PGlite:', result.rows?.length || 0)
setConnectors((result.rows || []).map(transformConnector))
);
console.log("📋 Fetched connectors from PGlite:", result.rows?.length || 0);
setConnectors((result.rows || []).map(transformConnector));
} catch (err) {
console.error('Failed to fetch connectors from PGlite:', err)
console.error("Failed to fetch connectors from PGlite:", err);
}
}
// Manual refresh function (optional, for fallback)
const refreshConnectors = useCallback(async () => {
if (!electric) return
await fetchConnectors(electric.db)
}, [electric])
if (!electric) return;
await fetchConnectors(electric.db);
}, [electric]);
return { connectors, loading, error, refreshConnectors }
return { connectors, loading, error, refreshConnectors };
}

View file

@ -1,190 +1,201 @@
"use client"
"use client";
import { useEffect, useState, useRef, useMemo } from 'react'
import { initElectric, type ElectricClient, type SyncHandle } from '@/lib/electric/client'
import { useEffect, useState, useRef, useMemo } from "react";
import { initElectric, type ElectricClient, type SyncHandle } from "@/lib/electric/client";
interface Document {
id: number
search_space_id: number
document_type: string
created_at: string
id: number;
search_space_id: number;
document_type: string;
created_at: string;
}
export function useDocumentsElectric(searchSpaceId: number | string | null) {
const [electric, setElectric] = useState<ElectricClient | null>(null)
const [documents, setDocuments] = useState<Document[]>([])
const [loading, setLoading] = useState(true)
const [error, setError] = useState<Error | null>(null)
const syncHandleRef = useRef<SyncHandle | null>(null)
const liveQueryRef = useRef<{ unsubscribe: () => void } | null>(null)
const [electric, setElectric] = useState<ElectricClient | null>(null);
const [documents, setDocuments] = useState<Document[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<Error | null>(null);
const syncHandleRef = useRef<SyncHandle | null>(null);
const liveQueryRef = useRef<{ unsubscribe: () => void } | null>(null);
// Calculate document type counts from synced documents
const documentTypeCounts = useMemo(() => {
if (!documents.length) return {}
const counts: Record<string, number> = {}
if (!documents.length) return {};
const counts: Record<string, number> = {};
for (const doc of documents) {
counts[doc.document_type] = (counts[doc.document_type] || 0) + 1
counts[doc.document_type] = (counts[doc.document_type] || 0) + 1;
}
return counts
}, [documents])
return counts;
}, [documents]);
// Initialize Electric SQL and start syncing with real-time updates
useEffect(() => {
if (!searchSpaceId) {
setLoading(false)
setDocuments([])
return
setLoading(false);
setDocuments([]);
return;
}
let mounted = true
let mounted = true;
async function init() {
try {
const electricClient = await initElectric()
if (!mounted) return
const electricClient = await initElectric();
if (!mounted) return;
setElectric(electricClient)
setElectric(electricClient);
// Start syncing documents for this search space via Electric SQL
// Only sync id, document_type, search_space_id columns for efficiency
console.log('Starting Electric SQL sync for documents, search_space_id:', searchSpaceId)
console.log("Starting Electric SQL sync for documents, search_space_id:", searchSpaceId);
const handle = await electricClient.syncShape({
table: 'documents',
table: "documents",
where: `search_space_id = ${searchSpaceId}`,
columns: ['id', 'document_type', 'search_space_id', 'created_at'],
primaryKey: ['id'],
})
console.log('Electric SQL sync started for documents:', {
columns: ["id", "document_type", "search_space_id", "created_at"],
primaryKey: ["id"],
});
console.log("Electric SQL sync started for documents:", {
isUpToDate: handle.isUpToDate,
hasStream: !!handle.stream,
hasInitialSyncPromise: !!handle.initialSyncPromise,
})
});
// Optimized: Check if already up-to-date before waiting
if (handle.isUpToDate) {
console.log('Documents sync already up-to-date, skipping wait')
console.log("Documents sync already up-to-date, skipping wait");
} else if (handle.initialSyncPromise) {
// Only wait if not already up-to-date
console.log('Waiting for initial documents sync to complete...')
console.log("Waiting for initial documents sync to complete...");
try {
// Use Promise.race with a shorter timeout to avoid long waits
await Promise.race([
handle.initialSyncPromise,
new Promise(resolve => setTimeout(resolve, 2000)), // Max 2s wait
])
console.log('Initial documents sync promise resolved or timed out, checking status:', {
new Promise((resolve) => setTimeout(resolve, 2000)), // Max 2s wait
]);
console.log("Initial documents sync promise resolved or timed out, checking status:", {
isUpToDate: handle.isUpToDate,
})
});
} catch (syncErr) {
console.error('Initial documents sync failed:', syncErr)
console.error("Initial documents sync failed:", syncErr);
}
}
// Check status after waiting
console.log('Documents sync status after waiting:', {
console.log("Documents sync status after waiting:", {
isUpToDate: handle.isUpToDate,
hasStream: !!handle.stream,
})
});
if (!mounted) {
handle.unsubscribe()
return
handle.unsubscribe();
return;
}
syncHandleRef.current = handle
setLoading(false)
setError(null)
syncHandleRef.current = handle;
setLoading(false);
setError(null);
// Fetch documents after sync is complete (we already waited above)
await fetchDocuments(electricClient.db)
await fetchDocuments(electricClient.db);
// Set up real-time updates using PGlite live queries
// Electric SQL syncs data to PGlite in real-time via HTTP streaming
// PGlite live queries detect when the synced data changes and trigger callbacks
try {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const db = electricClient.db as any
const db = electricClient.db as any;
// Use PGlite's live query API for real-time updates
// CORRECT API: await db.live.query() then use .subscribe()
if (db.live?.query && typeof db.live.query === 'function') {
if (db.live?.query && typeof db.live.query === "function") {
// IMPORTANT: db.live.query() returns a Promise - must await it!
const liveQuery = await db.live.query(
`SELECT id, document_type, search_space_id, created_at FROM documents WHERE search_space_id = $1 ORDER BY created_at DESC`,
[searchSpaceId]
)
);
if (!mounted) {
liveQuery.unsubscribe?.()
return
liveQuery.unsubscribe?.();
return;
}
// Set initial results immediately from the resolved query
if (liveQuery.initialResults?.rows) {
console.log('📋 Initial live query results for documents:', liveQuery.initialResults.rows.length)
setDocuments(liveQuery.initialResults.rows)
console.log(
"📋 Initial live query results for documents:",
liveQuery.initialResults.rows.length
);
setDocuments(liveQuery.initialResults.rows);
} else if (liveQuery.rows) {
// Some versions have rows directly on the result
console.log('📋 Initial live query results for documents (direct):', liveQuery.rows.length)
setDocuments(liveQuery.rows)
console.log(
"📋 Initial live query results for documents (direct):",
liveQuery.rows.length
);
setDocuments(liveQuery.rows);
}
// Subscribe to changes - this is the correct API!
// The callback fires automatically when Electric SQL syncs new data to PGlite
if (typeof liveQuery.subscribe === 'function') {
if (typeof liveQuery.subscribe === "function") {
liveQuery.subscribe((result: { rows: Document[] }) => {
if (mounted && result.rows) {
console.log('🔄 Documents updated via live query:', result.rows.length)
setDocuments(result.rows)
console.log("🔄 Documents updated via live query:", result.rows.length);
setDocuments(result.rows);
}
})
});
// Store unsubscribe function for cleanup
liveQueryRef.current = liveQuery
liveQueryRef.current = liveQuery;
}
} else {
console.warn('PGlite live query API not available for documents, falling back to polling')
console.warn(
"PGlite live query API not available for documents, falling back to polling"
);
}
} catch (liveQueryErr) {
console.error('Failed to set up live query for documents:', liveQueryErr)
console.error("Failed to set up live query for documents:", liveQueryErr);
// Don't fail completely - we still have the initial fetch
}
} catch (err) {
console.error('Failed to initialize Electric SQL for documents:', err)
console.error("Failed to initialize Electric SQL for documents:", err);
if (mounted) {
setError(err instanceof Error ? err : new Error('Failed to initialize Electric SQL for documents'))
setLoading(false)
setError(
err instanceof Error
? err
: new Error("Failed to initialize Electric SQL for documents")
);
setLoading(false);
}
}
}
init()
init();
return () => {
mounted = false
syncHandleRef.current?.unsubscribe?.()
liveQueryRef.current?.unsubscribe?.()
syncHandleRef.current = null
liveQueryRef.current = null
}
}, [searchSpaceId])
mounted = false;
syncHandleRef.current?.unsubscribe?.();
liveQueryRef.current?.unsubscribe?.();
syncHandleRef.current = null;
liveQueryRef.current = null;
};
}, [searchSpaceId]);
async function fetchDocuments(db: any) {
try {
const result = await db.query(
`SELECT id, document_type, search_space_id, created_at FROM documents WHERE search_space_id = $1 ORDER BY created_at DESC`,
[searchSpaceId]
)
console.log('📋 Fetched documents from PGlite:', result.rows?.length || 0)
setDocuments(result.rows || [])
);
console.log("📋 Fetched documents from PGlite:", result.rows?.length || 0);
setDocuments(result.rows || []);
} catch (err) {
console.error('Failed to fetch documents from PGlite:', err)
console.error("Failed to fetch documents from PGlite:", err);
}
}
return { documentTypeCounts, loading, error }
return { documentTypeCounts, loading, error };
}

View file

@ -1,211 +1,226 @@
"use client"
"use client";
import { useEffect, useState, useCallback, useRef } from 'react'
import { initElectric, isElectricInitialized, type ElectricClient, type SyncHandle } from '@/lib/electric/client'
import type { Notification } from '@/contracts/types/notification.types'
import { useEffect, useState, useCallback, useRef } from "react";
import {
initElectric,
isElectricInitialized,
type ElectricClient,
type SyncHandle,
} from "@/lib/electric/client";
import type { Notification } from "@/contracts/types/notification.types";
export type { Notification } from '@/contracts/types/notification.types'
export type { Notification } from "@/contracts/types/notification.types";
export function useNotifications(userId: string | null) {
const [electric, setElectric] = useState<ElectricClient | null>(null)
const [notifications, setNotifications] = useState<Notification[]>([])
const [loading, setLoading] = useState(true)
const [error, setError] = useState<Error | null>(null)
const syncHandleRef = useRef<SyncHandle | null>(null)
const liveQueryRef = useRef<{ unsubscribe: () => void } | null>(null)
const [electric, setElectric] = useState<ElectricClient | null>(null);
const [notifications, setNotifications] = useState<Notification[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<Error | null>(null);
const syncHandleRef = useRef<SyncHandle | null>(null);
const liveQueryRef = useRef<{ unsubscribe: () => void } | null>(null);
// Use ref instead of state to track initialization - prevents cleanup from running when set
const initializedRef = useRef(false)
const initializedRef = useRef(false);
// Initialize Electric SQL and start syncing with real-time updates
useEffect(() => {
// Use ref to prevent re-initialization without triggering cleanup
if (!userId || initializedRef.current) return
initializedRef.current = true
if (!userId || initializedRef.current) return;
initializedRef.current = true;
let mounted = true
let mounted = true;
async function init() {
try {
const electricClient = await initElectric()
if (!mounted) return
const electricClient = await initElectric();
if (!mounted) return;
setElectric(electricClient)
setElectric(electricClient);
// Start syncing notifications for this user via Electric SQL
// Note: user_id is stored as TEXT in PGlite (UUID from backend is converted)
console.log('Starting Electric SQL sync for user:', userId)
console.log("Starting Electric SQL sync for user:", userId);
// Use string format for WHERE clause (PGlite sync plugin expects this format)
// The user_id is a UUID string, so we need to quote it properly
const handle = await electricClient.syncShape({
table: 'notifications',
table: "notifications",
where: `user_id = '${userId}'`,
primaryKey: ['id'],
})
console.log('Electric SQL sync started:', {
primaryKey: ["id"],
});
console.log("Electric SQL sync started:", {
isUpToDate: handle.isUpToDate,
hasStream: !!handle.stream,
hasInitialSyncPromise: !!handle.initialSyncPromise,
})
});
// Optimized: Check if already up-to-date before waiting
if (handle.isUpToDate) {
console.log('Sync already up-to-date, skipping wait')
console.log("Sync already up-to-date, skipping wait");
} else if (handle.initialSyncPromise) {
// Only wait if not already up-to-date
console.log('Waiting for initial sync to complete...')
console.log("Waiting for initial sync to complete...");
try {
// Use Promise.race with a shorter timeout to avoid long waits
await Promise.race([
handle.initialSyncPromise,
new Promise(resolve => setTimeout(resolve, 2000)), // Max 2s wait
])
console.log('Initial sync promise resolved or timed out, checking status:', {
new Promise((resolve) => setTimeout(resolve, 2000)), // Max 2s wait
]);
console.log("Initial sync promise resolved or timed out, checking status:", {
isUpToDate: handle.isUpToDate,
})
});
} catch (syncErr) {
console.error('Initial sync failed:', syncErr)
console.error("Initial sync failed:", syncErr);
}
}
// Check status after waiting
console.log('Sync status after waiting:', {
console.log("Sync status after waiting:", {
isUpToDate: handle.isUpToDate,
hasStream: !!handle.stream,
})
});
if (!mounted) {
handle.unsubscribe()
return
handle.unsubscribe();
return;
}
syncHandleRef.current = handle
setLoading(false)
setError(null)
syncHandleRef.current = handle;
setLoading(false);
setError(null);
// Fetch notifications after sync is complete (we already waited above)
await fetchNotifications(electricClient.db)
await fetchNotifications(electricClient.db);
// Set up real-time updates using PGlite live queries
// Electric SQL syncs data to PGlite in real-time via HTTP streaming
// PGlite live queries detect when the synced data changes and trigger callbacks
try {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const db = electricClient.db as any
const db = electricClient.db as any;
// Use PGlite's live query API for real-time updates
// CORRECT API: await db.live.query() then use .subscribe()
if (db.live?.query && typeof db.live.query === 'function') {
if (db.live?.query && typeof db.live.query === "function") {
// IMPORTANT: db.live.query() returns a Promise - must await it!
const liveQuery = await db.live.query(
`SELECT * FROM notifications WHERE user_id = $1 ORDER BY created_at DESC`,
[userId]
)
);
if (!mounted) {
liveQuery.unsubscribe?.()
return
liveQuery.unsubscribe?.();
return;
}
// Set initial results immediately from the resolved query
if (liveQuery.initialResults?.rows) {
console.log('📋 Initial live query results:', liveQuery.initialResults.rows.length)
setNotifications(liveQuery.initialResults.rows)
console.log("📋 Initial live query results:", liveQuery.initialResults.rows.length);
setNotifications(liveQuery.initialResults.rows);
} else if (liveQuery.rows) {
// Some versions have rows directly on the result
console.log('📋 Initial live query results (direct):', liveQuery.rows.length)
setNotifications(liveQuery.rows)
console.log("📋 Initial live query results (direct):", liveQuery.rows.length);
setNotifications(liveQuery.rows);
}
// Subscribe to changes - this is the correct API!
// The callback fires automatically when Electric SQL syncs new data to PGlite
if (typeof liveQuery.subscribe === 'function') {
if (typeof liveQuery.subscribe === "function") {
liveQuery.subscribe((result: { rows: Notification[] }) => {
console.log('🔔 Live query update received:', result.rows?.length || 0, 'notifications')
console.log(
"🔔 Live query update received:",
result.rows?.length || 0,
"notifications"
);
if (mounted && result.rows) {
setNotifications(result.rows)
setNotifications(result.rows);
}
})
console.log('✅ Real-time notifications enabled via PGlite live queries')
});
console.log("✅ Real-time notifications enabled via PGlite live queries");
} else {
console.warn('⚠️ Live query subscribe method not available')
console.warn("⚠️ Live query subscribe method not available");
}
// Store for cleanup
if (typeof liveQuery.unsubscribe === 'function') {
liveQueryRef.current = liveQuery
if (typeof liveQuery.unsubscribe === "function") {
liveQueryRef.current = liveQuery;
}
} else {
console.error('❌ PGlite live queries not available - db.live.query is not a function')
console.log('db.live:', db.live)
console.error("❌ PGlite live queries not available - db.live.query is not a function");
console.log("db.live:", db.live);
}
} catch (liveErr) {
console.error('❌ Failed to set up real-time updates:', liveErr)
console.error("❌ Failed to set up real-time updates:", liveErr);
}
} catch (err) {
if (!mounted) return
console.error('Failed to initialize Electric SQL:', err)
setError(err instanceof Error ? err : new Error('Failed to initialize Electric SQL'))
if (!mounted) return;
console.error("Failed to initialize Electric SQL:", err);
setError(err instanceof Error ? err : new Error("Failed to initialize Electric SQL"));
// Still mark as loaded so the UI doesn't block
setLoading(false)
setLoading(false);
}
}
async function fetchNotifications(db: InstanceType<typeof import('@electric-sql/pglite').PGlite>) {
async function fetchNotifications(
db: InstanceType<typeof import("@electric-sql/pglite").PGlite>
) {
try {
// Debug: Check all notifications first
const allNotifications = await db.query<Notification>(
`SELECT * FROM notifications ORDER BY created_at DESC`
)
console.log('All notifications in PGlite:', allNotifications.rows?.length || 0, allNotifications.rows)
);
console.log(
"All notifications in PGlite:",
allNotifications.rows?.length || 0,
allNotifications.rows
);
// Use PGlite's query method (not exec for SELECT queries)
const result = await db.query<Notification>(
`SELECT * FROM notifications
WHERE user_id = $1
ORDER BY created_at DESC`,
[userId]
)
console.log(`Notifications for user ${userId}:`, result.rows?.length || 0, result.rows)
);
console.log(`Notifications for user ${userId}:`, result.rows?.length || 0, result.rows);
if (mounted) {
// PGlite query returns { rows: [] } format
setNotifications(result.rows || [])
setNotifications(result.rows || []);
}
} catch (err) {
console.error('Failed to fetch notifications:', err)
console.error("Failed to fetch notifications:", err);
// Log more details for debugging
console.error('Error details:', err)
console.error("Error details:", err);
}
}
init()
init();
return () => {
mounted = false
mounted = false;
// Reset initialization state so we can reinitialize with a new userId
initializedRef.current = false
setLoading(true)
initializedRef.current = false;
setLoading(true);
if (syncHandleRef.current) {
syncHandleRef.current.unsubscribe()
syncHandleRef.current = null
syncHandleRef.current.unsubscribe();
syncHandleRef.current = null;
}
if (liveQueryRef.current) {
liveQueryRef.current.unsubscribe()
liveQueryRef.current = null
liveQueryRef.current.unsubscribe();
liveQueryRef.current = null;
}
}
// Only depend on userId - using ref for initialization tracking to prevent cleanup issues
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [userId])
};
// Only depend on userId - using ref for initialization tracking to prevent cleanup issues
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [userId]);
// Mark notification as read (local only - needs backend sync)
const markAsRead = useCallback(
async (notificationId: number) => {
if (!electric || !isElectricInitialized()) {
console.warn('Electric SQL not initialized')
return false
console.warn("Electric SQL not initialized");
return false;
}
try {
@ -213,46 +228,46 @@ export function useNotifications(userId: string | null) {
await electric.db.query(
`UPDATE notifications SET read = true, updated_at = NOW() WHERE id = $1`,
[notificationId]
)
);
// Update local state
setNotifications(prev =>
prev.map(n => n.id === notificationId ? { ...n, read: true } : n)
)
setNotifications((prev) =>
prev.map((n) => (n.id === notificationId ? { ...n, read: true } : n))
);
// TODO: Also send to backend to persist the change
// This could be done via a REST API call
return true
return true;
} catch (err) {
console.error('Failed to mark notification as read:', err)
return false
console.error("Failed to mark notification as read:", err);
return false;
}
},
[electric]
)
);
// Mark all notifications as read
const markAllAsRead = useCallback(async () => {
if (!electric || !isElectricInitialized()) {
console.warn('Electric SQL not initialized')
return false
console.warn("Electric SQL not initialized");
return false;
}
try {
const unread = notifications.filter(n => !n.read)
const unread = notifications.filter((n) => !n.read);
for (const notification of unread) {
await markAsRead(notification.id)
await markAsRead(notification.id);
}
return true
return true;
} catch (err) {
console.error('Failed to mark all notifications as read:', err)
return false
console.error("Failed to mark all notifications as read:", err);
return false;
}
}, [electric, notifications, markAsRead])
}, [electric, notifications, markAsRead]);
// Get unread count
const unreadCount = notifications.filter(n => !n.read).length
const unreadCount = notifications.filter((n) => !n.read).length;
return {
notifications,
@ -261,5 +276,5 @@ export function useNotifications(userId: string | null) {
markAllAsRead,
loading,
error,
}
};
}