import { useEffect } from 'react'; import { Page, Block, List, ListItem, Spinner, Tag } from '@cap-rel/smartcommon'; import { useApi, useStates } from '@cap-rel/smartcommon'; import { useOfflineSync } from '../../hooks/useOfflineSync'; export const TasksPage = () => { const api = useApi(); const { db, isOnline, isSyncing, sync, queueAction } = useOfflineSync(); const st = useStates({ initialStates: { tasks: [], loading: true } }); useEffect(() => { loadTasks(); }, []); const loadTasks = async () => { st.set('loading', true); try { if (isOnline) { // En ligne : charger depuis l'API const data = await api.private.get('tasks').json(); // Sauvegarder localement await db.tasks.clear(); await db.tasks.bulkAdd(data.tasks.map(t => ({ ...t, synced: true }))); st.set('tasks', data.tasks); } else { // Hors ligne : charger depuis IndexedDB const localTasks = await db.tasks.toArray(); st.set('tasks', localTasks); } } catch (err) { // Erreur réseau : utiliser les données locales const localTasks = await db.tasks.toArray(); st.set('tasks', localTasks); } finally { st.set('loading', false); } }; const createTask = async (data) => { // Créer localement avec un ID temporaire const tempId = 'temp_' + Date.now(); const newTask = { ...data, id: tempId, synced: false }; await db.tasks.add(newTask); st.set('tasks', [...st.get('tasks'), newTask]); if (isOnline) { try { const result = await api.private.post('tasks', { json: data }).json(); // Remplacer l'ID temporaire par le vrai ID await db.tasks.update(tempId, { id: result.id, synced: true }); } catch (err) { // Ajouter à la queue pour sync ultérieure await queueAction('create', 'tasks', tempId, data); } } else { await queueAction('create', 'tasks', tempId, data); } }; return ( {/* Indicateur de statut */}
{isOnline ? 'En ligne' : 'Hors ligne'} {isSyncing && }
{/* Liste */} {st.get('tasks').map(task => ( ))}
); };