Skip to content

Commit e0021c0

Browse files
committed
fix: improve useDatabaseInitialization
1 parent d0eede5 commit e0021c0

File tree

1 file changed

+20
-11
lines changed

1 file changed

+20
-11
lines changed

src/core/database/useDatabaseInitialization.ts

Lines changed: 20 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { useState, useEffect, useRef } from 'react';
1+
import { useState, useEffect, useRef, useMemo } from 'react';
22
import type { DB } from '@op-engineering/op-sqlite';
33
import type { TableConfig } from '../../types/TableConfig';
44
import type { Logger } from '../common/logger';
@@ -126,15 +126,24 @@ export function useDatabaseInitialization(
126126
/** REFS */
127127
const writeDbRef = useRef<DB | null>(null);
128128
const readDbRef = useRef<DB | null>(null);
129+
const onDatabaseReadyRef = useRef(onDatabaseReady);
130+
131+
useEffect(() => {
132+
onDatabaseReadyRef.current = onDatabaseReady;
133+
}, [onDatabaseReady]);
129134

130135
/** SERIALIZED CONFIG - Prevents unnecessary re-initialization */
131-
const serializedConfig = JSON.stringify({
132-
connectionString,
133-
databaseName,
134-
tables: tablesToBeSynced,
135-
apiKey,
136-
accessToken,
137-
});
136+
const serializedConfig = useMemo(
137+
() =>
138+
JSON.stringify({
139+
connectionString,
140+
databaseName,
141+
tables: tablesToBeSynced,
142+
apiKey,
143+
accessToken,
144+
}),
145+
[connectionString, databaseName, tablesToBeSynced, apiKey, accessToken]
146+
);
138147

139148
/** INITIALIZATION EFFECT */
140149
useEffect(() => {
@@ -183,10 +192,10 @@ export function useDatabaseInitialization(
183192
logger.info('✅ Databases ready for local use');
184193

185194
/** RUN onDatabaseReady CALLBACK (e.g., migrations) */
186-
if (onDatabaseReady) {
195+
if (onDatabaseReadyRef.current) {
187196
logger.info('🔄 Running onDatabaseReady callback...');
188197
try {
189-
await onDatabaseReady(localWriteDb);
198+
await onDatabaseReadyRef.current(localWriteDb);
190199
logger.info('✅ onDatabaseReady callback completed');
191200
} catch (err) {
192201
logger.error('❌ onDatabaseReady callback failed:', err);
@@ -277,7 +286,7 @@ export function useDatabaseInitialization(
277286
}
278287
};
279288
// eslint-disable-next-line react-hooks/exhaustive-deps
280-
}, [serializedConfig, logger]);
289+
}, [serializedConfig]);
281290

282291
return {
283292
writeDb,

0 commit comments

Comments
 (0)