feat: implement add item page with image upload and form submission

This commit is contained in:
Greg 2025-05-18 23:19:19 +02:00
parent 36138478f8
commit 4c443fdbfe
2 changed files with 78 additions and 55 deletions

View File

@ -6,54 +6,19 @@ import { revalidatePath } from 'next/cache';
import { redirect } from 'next/navigation';
export async function createItem(formData) {
const BUCKET_NAME = 'item_images';
if (!supabase) {
return { error: 'Supabase client is not initialized. Cannot create item.' };
}
const pictureFile = formData.get('picture_file');
let pictureUrl = null;
if (pictureFile && pictureFile.size > 0) {
if (!supabase.storage) {
return { error: 'Supabase storage client is not available.' };
}
const fileName = `public/${Date.now()}-${pictureFile.name.replace(/[^a-zA-Z0-9.]/g, '_')}`;
const { data: uploadData, error: uploadError } = await supabase.storage
.from(BUCKET_NAME)
.upload(fileName, pictureFile);
if (uploadError) {
console.error('Supabase storage upload error:', uploadError);
return { error: `Failed to upload image: ${uploadError.message}` };
}
const { data: publicUrlData } = supabase.storage
.from(BUCKET_NAME)
.getPublicUrl(fileName);
if (!publicUrlData || !publicUrlData.publicUrl) {
console.error('Supabase storage getPublicUrl error: No publicUrl found');
// Optionally, you might want to delete the uploaded file here if getting URL fails
// await supabase.storage.from(BUCKET_NAME).remove([fileName]);
return { error: 'Failed to get image public URL after upload.' };
}
pictureUrl = publicUrlData.publicUrl;
} else {
// Handle case where no file is uploaded but form still has 'picture_url' field (e.g. from old version)
// Or simply rely on pictureUrl being null if no file is chosen.
const legacyPictureUrl = formData.get('picture_url');
if (legacyPictureUrl && typeof legacyPictureUrl === 'string' && legacyPictureUrl.startsWith('http')) {
pictureUrl = legacyPictureUrl; // Keep old URL if provided and no new file
}
}
// The picture_url is now received directly from the client
// after client-side upload to Supabase Storage
const newItem = {
title: formData.get('title'),
type: formData.get('type'),
rating: formData.get('rating') ? parseInt(formData.get('rating'), 10) : null,
notes: formData.get('notes'),
picture_url: pictureUrl,
picture_url: formData.get('picture_url'),
// created_at will be set by default in Supabase or can be added here if needed
};

View File

@ -1,9 +1,10 @@
// app/add-item/page.js
'use client';
import { useState, useTransition } from 'react';
import { useState, useTransition, useRef } from 'react';
import { createItem } from './actions'; // Server Action
import { useRouter } from 'next/navigation';
import { supabase } from '@/lib/supabaseClient';
export default function AddItemPage() {
const router = useRouter();
@ -11,24 +12,81 @@ export default function AddItemPage() {
const [error, setError] = useState(null);
const [successMessage, setSuccessMessage] = useState('');
const [isUploading, setIsUploading] = useState(false);
const formRef = useRef(null);
const handleSubmit = async (event) => {
event.preventDefault();
setError(null);
setSuccessMessage('');
const formData = new FormData(event.currentTarget);
setIsUploading(true);
try {
const formData = new FormData(event.currentTarget);
const pictureFile = formData.get('picture_file');
let pictureUrl = null;
startTransition(async () => {
const result = await createItem(formData);
if (result.error) {
setError(result.error);
} else if (result.success) {
setSuccessMessage(result.message);
// Optionally clear the form or redirect
event.target.reset(); // Clear form fields
// router.push('/'); // Or redirect to homepage after a delay
setTimeout(() => router.push('/'), 1500); // Redirect after 1.5s
// Handle image upload directly from client if a file is selected
if (pictureFile && pictureFile.size > 0) {
// Upload to Supabase Storage directly from client
const BUCKET_NAME = 'item_images';
const fileName = `public/${Date.now()}-${pictureFile.name.replace(/[^a-zA-Z0-9.]/g, '_')}`;
const { data: uploadData, error: uploadError } = await supabase.storage
.from(BUCKET_NAME)
.upload(fileName, pictureFile);
if (uploadError) {
throw new Error(`Failed to upload image: ${uploadError.message}`);
}
const { data: publicUrlData } = supabase.storage
.from(BUCKET_NAME)
.getPublicUrl(fileName);
if (!publicUrlData || !publicUrlData.publicUrl) {
throw new Error('Failed to get image public URL after upload.');
}
pictureUrl = publicUrlData.publicUrl;
}
});
// Create a new FormData without the file to reduce payload size
const serverFormData = new FormData();
serverFormData.append('title', formData.get('title'));
serverFormData.append('type', formData.get('type'));
if (formData.get('rating')) {
serverFormData.append('rating', formData.get('rating'));
}
if (formData.get('notes')) {
serverFormData.append('notes', formData.get('notes'));
}
// Send the image URL instead of the file
if (pictureUrl) {
serverFormData.append('picture_url', pictureUrl);
}
// Call server action with the form data (minus the image file)
startTransition(async () => {
const result = await createItem(serverFormData);
if (result.error) {
setError(result.error);
} else if (result.success) {
setSuccessMessage(result.message);
// Clear form fields
formRef.current.reset();
// Redirect after a delay
setTimeout(() => router.push('/'), 1500);
}
});
} catch (err) {
setError(err.message);
} finally {
setIsUploading(false);
}
};
return (
@ -53,7 +111,7 @@ export default function AddItemPage() {
</div>
)}
<form onSubmit={handleSubmit} className="space-y-6 bg-neutral-800 p-6 rounded-lg shadow-xl">
<form ref={formRef} onSubmit={handleSubmit} className="space-y-6 bg-neutral-800 p-6 rounded-lg shadow-xl">
<div>
<label htmlFor="title" className="block text-sm font-medium text-neutral-300 mb-1">Title <span className="text-red-500">*</span></label>
<input
@ -122,10 +180,10 @@ export default function AddItemPage() {
<div className="flex justify-end">
<button
type="submit"
disabled={isPending}
disabled={isPending || isUploading}
className="inline-flex items-center justify-center px-6 py-3 border border-transparent text-base font-medium rounded-md shadow-sm text-white bg-sky-600 hover:bg-sky-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-offset-neutral-800 focus:ring-sky-500 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
>
{isPending ? 'Adding Item...' : 'Add Item'}
{isUploading ? 'Uploading Image...' : isPending ? 'Adding Item...' : 'Add Item'}
</button>
</div>
</form>