Add react hooks & components to split up the profile page. Learning how to separate hooks

This commit is contained in:
2025-05-20 15:41:32 -05:00
parent 3dffa71a89
commit 408bb140ba
21 changed files with 679 additions and 269 deletions

View File

@ -0,0 +1,49 @@
import { useState, useRef } from 'react';
import { uploadFile } from '@/lib/actions';
import { toast } from 'sonner';
export const useFileUpload = () => {
const [isUploading, setIsUploading] = useState(false);
const fileInputRef = useRef<HTMLInputElement>(null);
const uploadToStorage = async (file: File, bucket: string) => {
try {
setIsUploading(true);
// Generate a unique filename to avoid collisions
const fileExt = file.name.split('.').pop();
const fileName = `${Date.now()}-${Math.random().toString(36).substring(2, 15)}.${fileExt}`;
// Upload the file to Supabase storage
const uploadResult = await uploadFile({
bucket,
path: fileName,
file,
options: {
upsert: true,
contentType: file.type,
},
});
if (!uploadResult.success) {
throw new Error(uploadResult.error || `Failed to upload to ${bucket}`);
}
return { success: true, path: uploadResult.data };
} catch (error) {
console.error(`Error uploading to ${bucket}:`, error);
toast.error(error instanceof Error ? error.message : `Failed to upload to ${bucket}`);
return { success: false, error };
} finally {
setIsUploading(false);
// Clear the input value so the same file can be selected again
if (fileInputRef.current) fileInputRef.current.value = '';
}
};
return {
isUploading,
fileInputRef,
uploadToStorage,
};
}