feat: implement add item page with image upload and form submission
This commit is contained in:
parent
36138478f8
commit
4c443fdbfe
@ -6,54 +6,19 @@ import { revalidatePath } from 'next/cache';
|
|||||||
import { redirect } from 'next/navigation';
|
import { redirect } from 'next/navigation';
|
||||||
|
|
||||||
export async function createItem(formData) {
|
export async function createItem(formData) {
|
||||||
const BUCKET_NAME = 'item_images';
|
|
||||||
if (!supabase) {
|
if (!supabase) {
|
||||||
return { error: 'Supabase client is not initialized. Cannot create item.' };
|
return { error: 'Supabase client is not initialized. Cannot create item.' };
|
||||||
}
|
}
|
||||||
|
|
||||||
const pictureFile = formData.get('picture_file');
|
// The picture_url is now received directly from the client
|
||||||
let pictureUrl = null;
|
// after client-side upload to Supabase Storage
|
||||||
|
|
||||||
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
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const newItem = {
|
const newItem = {
|
||||||
title: formData.get('title'),
|
title: formData.get('title'),
|
||||||
type: formData.get('type'),
|
type: formData.get('type'),
|
||||||
rating: formData.get('rating') ? parseInt(formData.get('rating'), 10) : null,
|
rating: formData.get('rating') ? parseInt(formData.get('rating'), 10) : null,
|
||||||
notes: formData.get('notes'),
|
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
|
// created_at will be set by default in Supabase or can be added here if needed
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@ -1,9 +1,10 @@
|
|||||||
// app/add-item/page.js
|
// app/add-item/page.js
|
||||||
'use client';
|
'use client';
|
||||||
|
|
||||||
import { useState, useTransition } from 'react';
|
import { useState, useTransition, useRef } from 'react';
|
||||||
import { createItem } from './actions'; // Server Action
|
import { createItem } from './actions'; // Server Action
|
||||||
import { useRouter } from 'next/navigation';
|
import { useRouter } from 'next/navigation';
|
||||||
|
import { supabase } from '@/lib/supabaseClient';
|
||||||
|
|
||||||
export default function AddItemPage() {
|
export default function AddItemPage() {
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
@ -11,24 +12,81 @@ export default function AddItemPage() {
|
|||||||
const [error, setError] = useState(null);
|
const [error, setError] = useState(null);
|
||||||
const [successMessage, setSuccessMessage] = useState('');
|
const [successMessage, setSuccessMessage] = useState('');
|
||||||
|
|
||||||
|
const [isUploading, setIsUploading] = useState(false);
|
||||||
|
const formRef = useRef(null);
|
||||||
|
|
||||||
const handleSubmit = async (event) => {
|
const handleSubmit = async (event) => {
|
||||||
event.preventDefault();
|
event.preventDefault();
|
||||||
setError(null);
|
setError(null);
|
||||||
setSuccessMessage('');
|
setSuccessMessage('');
|
||||||
const formData = new FormData(event.currentTarget);
|
setIsUploading(true);
|
||||||
|
|
||||||
startTransition(async () => {
|
try {
|
||||||
const result = await createItem(formData);
|
const formData = new FormData(event.currentTarget);
|
||||||
if (result.error) {
|
const pictureFile = formData.get('picture_file');
|
||||||
setError(result.error);
|
let pictureUrl = null;
|
||||||
} else if (result.success) {
|
|
||||||
setSuccessMessage(result.message);
|
// Handle image upload directly from client if a file is selected
|
||||||
// Optionally clear the form or redirect
|
if (pictureFile && pictureFile.size > 0) {
|
||||||
event.target.reset(); // Clear form fields
|
// Upload to Supabase Storage directly from client
|
||||||
// router.push('/'); // Or redirect to homepage after a delay
|
const BUCKET_NAME = 'item_images';
|
||||||
setTimeout(() => router.push('/'), 1500); // Redirect after 1.5s
|
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 (
|
return (
|
||||||
@ -53,7 +111,7 @@ export default function AddItemPage() {
|
|||||||
</div>
|
</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>
|
<div>
|
||||||
<label htmlFor="title" className="block text-sm font-medium text-neutral-300 mb-1">Title <span className="text-red-500">*</span></label>
|
<label htmlFor="title" className="block text-sm font-medium text-neutral-300 mb-1">Title <span className="text-red-500">*</span></label>
|
||||||
<input
|
<input
|
||||||
@ -122,10 +180,10 @@ export default function AddItemPage() {
|
|||||||
<div className="flex justify-end">
|
<div className="flex justify-end">
|
||||||
<button
|
<button
|
||||||
type="submit"
|
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"
|
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>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
</form>
|
</form>
|
||||||
|
|||||||
Loading…
x
Reference in New Issue
Block a user