--- source_hash: "8347410f" title: "Chapter 3: Utility Hooks" weight: 600 --- # Chapter 3: Utility Hooks SmartCommon provides utility hooks for common tasks. ## useNavigation Programmatic navigation with React Router. ```javascript import { useNavigation } from '@cap-rel/smartcommon'; function MyComponent() { const nav = useNavigation(); return (
API URL: {config.api.prefixUrl}
Mode: {config.debug ? 'Debug' : 'Production'}
On {dateOnly} at {timeOnly}
Window: {windowDimension.w} x {windowDimension.h}
; } ``` ## useFile File manipulation utilities. ### Resize Image ```javascript import { useFile } from '@cap-rel/smartcommon'; function ImageUploader({ onUpload }) { const { resizeImage } = useFile(); const handleFileChange = async (e) => { const file = e.target.files[0]; if (!file) return; // Resize before upload const base64 = await resizeImage(file, { maxWidth: 1920, maxHeight: 1080, quality: 85 }); // base64 = "data:image/jpeg;base64,..." onUpload(base64); }; return ( ); } ``` ## useDb IndexedDB database via Dexie for local storage of large amounts of data. > In an application, the database is declared once in `src/db/index.js` with > the `Db` class, then imported by the business hooks (see > [Data storage](/front/stockage-de-donnees)). The examples below show the > Dexie API on an isolated component. ### Configuration ```javascript import { useDb } from '@cap-rel/smartcommon'; const db = useDb({ name: 'myApp', version: 1, stores: { items: '++id, name, category, createdAt', categories: '++id, name' }, debug: true }); ``` ### CRUD Operations ```javascript function ItemsManager() { const db = useDb({ name: 'myApp', version: 1, stores: { items: '++id, name, category' } }); // Create const addItem = async (item) => { const id = await db.items.add(item); console.log('Item created with id:', id); return id; }; // Read all const getAllItems = async () => { return db.items.toArray(); }; // Read one const getItem = async (id) => { return db.items.get(id); }; // Update const updateItem = async (id, changes) => { await db.items.update(id, changes); }; // Delete const deleteItem = async (id) => { await db.items.delete(id); }; // ... } ``` ### Advanced Queries ```javascript // Filter by value const electronics = await db.items .where('category') .equals('electronics') .toArray(); // Filter by range const expensiveItems = await db.items .where('price') .above(100) .toArray(); // Sort const sorted = await db.items .orderBy('createdAt') .reverse() .toArray(); // Limit const first10 = await db.items .limit(10) .toArray(); // Count const count = await db.items.count(); // Text search const matching = await db.items .filter(item => item.name.includes('test')) .toArray(); ``` ### Example: Offline Mode ```javascript import { useEffect } from 'react'; import { useApi, useDb, useStates } from '@cap-rel/smartcommon'; function OfflineCapableList() { const api = useApi(); const db = useDb({ name: 'myApp', version: 1, stores: { items: 'id, name, synced' } }); const st = useStates({ initialStates: { items: [], loading: true } }); useEffect(() => { loadItems(); }, []); const loadItems = async () => { try { // Try to load from API const data = await api.private.get('items').json(); // Save locally await db.items.clear(); await db.items.bulkAdd(data.map(i => ({ ...i, synced: true }))); st.set('items', data); } catch (err) { // On network error, load from IndexedDB console.log('Offline mode - loading local'); const localItems = await db.items.toArray(); st.set('items', localItems); } finally { st.set('loading', false); } }; const addItem = async (item) => { // Save locally first const id = await db.items.add({ ...item, synced: false }); // Update UI st.set('items', [...st.get('items'), { ...item, id }]); // Try to sync try { const result = await api.private.post('items', { json: item }).json(); await db.items.update(id, { ...result, synced: true }); } catch (err) { console.log('Sync failed, will retry later'); } }; // ... } ``` ## useAnimation Animation management with Framer Motion. ```javascript import { useAnimation } from '@cap-rel/smartcommon'; import { motion } from 'framer-motion'; function AnimatedList({ items }) { const { start } = useAnimation(); return (