Refactor code based on feedback

Refactor the code based on the provided feedback.
This commit is contained in:
gpt-engineer-app[bot]
2025-03-23 10:22:23 +00:00
parent ce60f418fa
commit d216daf2f4
6 changed files with 870 additions and 93 deletions

View File

@@ -0,0 +1,105 @@
/**
* 최적화된 데이터 동기화 훅
*/
import { useEffect, useState, useCallback } from 'react';
import { useAuth } from '@/contexts/auth';
import { optimizedSync, debouncedSync, throttledSync } from '@/utils/sync/syncOptimizer';
import { isSyncEnabled } from '@/utils/syncUtils';
import { emitEvent, APP_EVENTS } from '@/utils/eventEmitter';
export function useOptimizedDataSync() {
const { user } = useAuth();
const [isSyncing, setIsSyncing] = useState(false);
const [lastSyncTime, setLastSyncTime] = useState<string | null>(
localStorage.getItem('lastSyncTime')
);
// 동기화 상태 추적
useEffect(() => {
// 동기화 완료 이벤트 리스너
const handleSyncComplete = (e: CustomEvent) => {
setIsSyncing(false);
// 성공 시 마지막 동기화 시간 업데이트
if (e.detail?.success) {
const time = new Date().toISOString();
setLastSyncTime(time);
localStorage.setItem('lastSyncTime', time);
}
};
// 동기화 시작 이벤트 리스너
const handleSyncStart = () => {
setIsSyncing(true);
};
// 이벤트 리스너 등록
window.addEventListener(APP_EVENTS.SYNC_STARTED, handleSyncStart as EventListener);
window.addEventListener(APP_EVENTS.SYNC_COMPLETED, handleSyncComplete as EventListener);
window.addEventListener(APP_EVENTS.SYNC_FAILED, () => setIsSyncing(false));
return () => {
// 이벤트 리스너 제거
window.removeEventListener(APP_EVENTS.SYNC_STARTED, handleSyncStart as EventListener);
window.removeEventListener(APP_EVENTS.SYNC_COMPLETED, handleSyncComplete as EventListener);
window.removeEventListener(APP_EVENTS.SYNC_FAILED, () => setIsSyncing(false));
};
}, []);
// 즉시 동기화 실행 함수
const syncNow = useCallback(async () => {
if (!user || !isSyncEnabled() || isSyncing) return false;
try {
// 동기화 시작 이벤트 발생
emitEvent(APP_EVENTS.SYNC_STARTED);
// 동기화 실행
const result = await optimizedSync(user.id);
// 동기화 완료 이벤트 발생
emitEvent(APP_EVENTS.SYNC_COMPLETED, { success: result.success, data: result });
return result.success;
} catch (error) {
// 동기화 실패 이벤트 발생
emitEvent(APP_EVENTS.SYNC_FAILED, { error });
console.error('[동기화] 오류:', error);
return false;
}
}, [user, isSyncing]);
// 자동 동기화 (페이지 로드 시)
useEffect(() => {
if (user && isSyncEnabled()) {
// 페이지 로드 시 한 번 실행 (스로틀 적용)
const syncOnLoad = async () => {
await throttledSync(user.id);
};
// 페이지가 완전히 로드된 후 동기화 실행
const timer = setTimeout(syncOnLoad, 1000);
return () => clearTimeout(timer);
}
}, [user]);
// 디바운스된 동기화 함수
const debouncedSyncNow = useCallback(() => {
if (!user || !isSyncEnabled()) return;
// 동기화 시작 이벤트 발생 (UI 업데이트용)
emitEvent(APP_EVENTS.SYNC_STARTED);
// 디바운스된 동기화 실행
debouncedSync(user.id);
}, [user]);
return {
isSyncing,
lastSyncTime,
syncNow,
debouncedSyncNow
};
}