Files
tfm_ainventory/frontend/hooks/useSync.ts

40 lines
1.1 KiB
TypeScript

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
};
}