uploadForm.tsx 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. "use client";
  2. import { useKindeBrowserClient } from "@kinde-oss/kinde-auth-nextjs";
  3. import { useState } from "react";
  4. import { useQueryClient } from "@tanstack/react-query";
  5. interface FileData {
  6. id: string;
  7. filename: string;
  8. mimetype: string;
  9. size: number;
  10. createdAt: string;
  11. updatedAt: string;
  12. }
  13. export const UploadForm = ({ onFileUploaded }: { onFileUploaded?: (file: FileData) => void }) => {
  14. const [isUploading, setIsUploading] = useState(false);
  15. const queryClient = useQueryClient();
  16. const { user } = useKindeBrowserClient();
  17. const handleFileUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
  18. if (e.target.files && e.target.files[0]) {
  19. setIsUploading(true);
  20. const file = e.target.files[0];
  21. try {
  22. // Import the server action
  23. const { uploadFile } = await import('../actions/file-upload');
  24. const userId = user?.id ? user.id : "unknown-user-id";
  25. const uploadedFile = await uploadFile(file, userId);
  26. // Invalidate the files query to trigger a refresh
  27. await queryClient.invalidateQueries({ queryKey: ["files"] });
  28. // Call the callback if provided
  29. if (onFileUploaded) {
  30. onFileUploaded(uploadedFile);
  31. }
  32. // Reset the file input
  33. e.target.value = '';
  34. } catch (error) {
  35. console.error("Upload error:", error);
  36. alert("Failed to upload file");
  37. } finally {
  38. setIsUploading(false);
  39. }
  40. }
  41. };
  42. return (
  43. <div>
  44. <input
  45. type="file"
  46. name="file"
  47. onChange={handleFileUpload}
  48. disabled={isUploading}
  49. className="block w-full text-sm text-gray-500 file:mr-4 file:py-2 file:px-4 file:rounded-full file:border-0 file:text-sm file:font-semibold file:bg-blue-50 file:text-blue-700 hover:file:bg-blue-100"
  50. />
  51. {isUploading && (
  52. <div className="mt-2 text-sm text-gray-600">Uploading...</div>
  53. )}
  54. </div>
  55. );
  56. };