Skip to content

Instantly share code, notes, and snippets.

@mmikhan
Created December 28, 2024 14:38
Show Gist options
  • Save mmikhan/911d455b92b4aae2d611740b52a5d215 to your computer and use it in GitHub Desktop.
Save mmikhan/911d455b92b4aae2d611740b52a5d215 to your computer and use it in GitHub Desktop.
Upload Thing reusable client component
"use client";
import { useState } from "react";
import { generateReactHelpers } from "@uploadthing/react";
import type { OurFileRouter } from "@/app/api/uploadthing/core";
export const { uploadFiles } = generateReactHelpers<OurFileRouter>();
interface FormData {
name: string;
}
interface UploadImageProps {
onUploadComplete: (url: string, formData: FormData) => void;
onUploadError: (error: Error) => void;
}
export function useUploadImage({
onUploadComplete,
onUploadError,
}: UploadImageProps) {
const [uploading, setUploading] = useState(false);
const handleUpload = async (file: File, formData: FormData) => {
try {
setUploading(true);
const [res] = await uploadFiles(
(routeRegistry) => routeRegistry.imageUploader,
{ files: [file] }
);
onUploadComplete(res.url, formData);
} catch (err) {
onUploadError(err as Error);
} finally {
setUploading(false);
}
};
return { handleUpload, uploading };
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment