import { useMutation } from "convex/react"; import { useCallback } from "react"; import type { ClientApi } from "../client/index.js"; import { uploadWithProgress } from "../client/upload.js"; /** * A hook that allows you to upload a file to R2. * * This hook can be used as is, or copied into your own code for customization * and tighter control. * * @param api - The client API object from the R2 component, including at least * `generateUploadUrl` and `syncMetadata`. * @returns A function that uploads a file to R2. */ export function useUploadFile( api: Pick, ) { const generateUploadUrl = useMutation(api.generateUploadUrl); const syncMetadata = useMutation(api.syncMetadata); return useCallback( async ( file: File, options?: { onProgress?: (progress: { loaded: number; total: number }) => void; }, ) => { const { url, key } = await generateUploadUrl(); await uploadWithProgress(url, file, options?.onProgress); await syncMetadata({ key }); return key; }, [generateUploadUrl, syncMetadata], ); }