Add react hooks & components to split up the profile page. Learning how to separate hooks
This commit is contained in:
49
src/lib/hooks/useFileUpload.ts
Normal file
49
src/lib/hooks/useFileUpload.ts
Normal 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,
|
||||
};
|
||||
}
|
Reference in New Issue
Block a user