Hey is a decentralized and permissionless social media app built with Lens Protocol 馃尶
at main 62 lines 1.8 kB view raw
1import type { NewAttachment } from "@hey/types/misc"; 2import { useCallback } from "react"; 3import { toast } from "sonner"; 4import { 5 compressFiles, 6 createPreviewAttachments, 7 validateFileSize 8} from "@/helpers/attachmentUtils"; 9import uploadToIPFS from "@/helpers/uploadToIPFS"; 10import { usePostAttachmentStore } from "@/store/non-persisted/post/usePostAttachmentStore"; 11 12const useUploadAttachments = () => { 13 const { 14 addAttachments, 15 removeAttachments, 16 setIsUploading, 17 updateAttachments 18 } = usePostAttachmentStore(); 19 20 const handleUploadAttachments = useCallback( 21 async (attachments: FileList): Promise<NewAttachment[]> => { 22 setIsUploading(true); 23 24 const files = Array.from(attachments); 25 const compressedFiles = await compressFiles(files); 26 27 if (!compressedFiles.every(validateFileSize)) { 28 setIsUploading(false); 29 return []; 30 } 31 32 const previewAttachments = createPreviewAttachments(compressedFiles); 33 const attachmentIds = previewAttachments.map(({ id }) => id as string); 34 35 addAttachments(previewAttachments); 36 37 try { 38 const uploaded = await uploadToIPFS(compressedFiles); 39 const result = uploaded.map((file, index) => ({ 40 ...previewAttachments[index], 41 mimeType: file.mimeType, 42 uri: file.uri 43 })); 44 45 updateAttachments(result); 46 setIsUploading(false); 47 48 return result; 49 } catch { 50 toast.error("Something went wrong while uploading!"); 51 removeAttachments(attachmentIds); 52 setIsUploading(false); 53 return []; 54 } 55 }, 56 [addAttachments, removeAttachments, setIsUploading, updateAttachments] 57 ); 58 59 return { handleUploadAttachments }; 60}; 61 62export default useUploadAttachments;