Last active
October 28, 2023 09:56
-
-
Save pontusab/7b08a42603afddc825516d4b93517622 to your computer and use it in GitHub Desktop.
component.tsx
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"use client"; | |
import { useUpload } from "@/hooks/useUpload"; | |
import { getSupabaseBrowserClient } from "@midday/supabase/browser-client"; | |
import { useDropzone } from "react-dropzone"; | |
export function Attachments({ id }) { | |
const supabase = getSupabaseBrowserClient(); | |
const [files, setFiles] = useState<Attachment[]>([]); | |
const { isLoading, uploadFile } = useUpload(); | |
const handleOnDelete = async (id: string) => { | |
setFiles((files) => files.filter((file) => file.id !== id)); | |
await deleteAttachment(supabase, id); | |
router.refresh(); | |
}; | |
const onDrop = async (acceptedFiles: Array<Attachment>) => { | |
setFiles((prev) => [...prev, ...acceptedFiles]); | |
const uploaded = await Promise.all( | |
acceptedFiles.map(async (acceptedFile) => { | |
const { path } = await uploadFile({ | |
bucketName: "documents", | |
path: `transactions/${id}`, | |
file: acceptedFile, | |
}); | |
return { | |
path, | |
name: acceptedFile.name, | |
size: acceptedFile.size, | |
transaction_id: id, | |
type: acceptedFile.type, | |
}; | |
}), | |
); | |
const newFiles = await createAttachments(supabase, uploaded); | |
const uniqueFiles = new Set([...files, ...newFiles]); | |
setFiles([...uniqueFiles]); | |
}; | |
const { getRootProps, getInputProps, isDragActive } = useDropzone({ onDrop }); | |
return ( | |
<div> | |
<div | |
className={cn( | |
"w-full h-[120px] border-dotted border-2 border-border rounded-xl text-center flex flex-col justify-center space-y-1 transition-colors text-[#606060]", | |
isDragActive && "bg-secondary text-white", | |
)} | |
{...getRootProps()} | |
> | |
<input {...getInputProps()} /> | |
{isDragActive ? ( | |
<div> | |
<p className="text-xs">Drop your files upload</p> | |
</div> | |
) : ( | |
<div> | |
<p className="text-xs"> | |
Drop your files here, or{" "} | |
<span className="underline underline-offset-1"> | |
click to browse. | |
</span> | |
</p> | |
<p className="text-xs text-dark-gray">3MB file limit.</p> | |
</div> | |
)} | |
</div> | |
<AnimatePresence> | |
<ul className="mt-4 space-y-4"> | |
{files.map((file, index) => ( | |
<Item | |
key={file.name} | |
file={file} | |
onDelete={() => handleOnDelete(file.id)} | |
/> | |
))} | |
</ul> | |
</AnimatePresence> | |
</div> | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment