useBlocks.ts
1 import useSWR from 'swr'; 2 import { fetchBlocks, fetchBlocksByIds, type BlocksResponse, type MemoryBlock } from '@/utils/blocks'; 3 4 /** 5 * Hook for fetching a list of MemoryBlocks 6 * @param branch - Optional branch name to fetch blocks from (defaults to 'main') 7 * @param namespace - Optional namespace to filter blocks (defaults to 'legacy') 8 */ 9 export function useBlocks(branch?: string, namespace?: string) { 10 const key = [ 11 'blocks', 12 ...(branch ? [branch] : []), 13 ...(namespace ? [namespace] : []) 14 ]; 15 const { data, error, isLoading, mutate } = useSWR(key, () => fetchBlocks(branch, namespace)); 16 17 return { 18 blocks: data as BlocksResponse | undefined, 19 isLoading, 20 isError: error, 21 mutate 22 }; 23 } 24 25 /** 26 * Hook for fetching multiple MemoryBlocks by their IDs 27 * @param ids - Array of block IDs to fetch 28 * @param branch - Optional branch name to fetch blocks from (defaults to 'main') 29 * @param namespace - Optional namespace to filter blocks (defaults to 'legacy') 30 */ 31 export function useBlocksByIds(ids: string[], branch?: string, namespace?: string) { 32 // Create a stable key that only changes when the actual IDs, branch, or namespace change 33 const key = ids.length > 0 ? ['blocks-by-ids', [...ids].sort().join(','), branch, namespace] : null; 34 35 const { data, error, isLoading, mutate } = useSWR( 36 key, 37 () => fetchBlocksByIds(ids, branch, namespace) 38 ); 39 40 return { 41 blocksMap: data as Map<string, MemoryBlock> | undefined, 42 isLoading, 43 isError: error, 44 mutate 45 }; 46 }