refactor: extract useSync hook from page.tsx
This commit is contained in:
39
frontend/hooks/useSync.ts
Normal file
39
frontend/hooks/useSync.ts
Normal file
@@ -0,0 +1,39 @@
|
||||
import { useCallback, useState } from 'react';
|
||||
import { toast } from 'react-hot-toast';
|
||||
import { syncOfflineOperations, fetchAndCacheItems } from '@/lib/sync';
|
||||
|
||||
interface UseSyncOptions {
|
||||
isOnline: boolean;
|
||||
currentUser: any;
|
||||
onInventoryUpdate?: (items: any[]) => void;
|
||||
}
|
||||
|
||||
export function useSync(options: UseSyncOptions) {
|
||||
const { isOnline, currentUser, onInventoryUpdate } = options;
|
||||
const [syncing, setSyncing] = useState(false);
|
||||
|
||||
const handleSync = useCallback(async () => {
|
||||
if (!isOnline || !currentUser) return;
|
||||
setSyncing(true);
|
||||
try {
|
||||
const result = await syncOfflineOperations(currentUser.id);
|
||||
if (result.success > 0) {
|
||||
toast.success(`Synced ${result.success} operations!`);
|
||||
}
|
||||
const fresh = await fetchAndCacheItems();
|
||||
if (onInventoryUpdate) {
|
||||
onInventoryUpdate(fresh);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Sync failed", error);
|
||||
toast.error("Sync failed");
|
||||
} finally {
|
||||
setSyncing(false);
|
||||
}
|
||||
}, [isOnline, currentUser, onInventoryUpdate]);
|
||||
|
||||
return {
|
||||
syncing,
|
||||
handleSync
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user