feat: add item editing functionality with image upload support

This commit is contained in:
Greg 2025-05-18 23:28:49 +02:00
parent 4c443fdbfe
commit cde9020bb6
3 changed files with 402 additions and 8 deletions

View File

@ -0,0 +1,61 @@
// app/edit-item/[id]/actions.js
'use server';
import { supabase } from '@/lib/supabaseClient';
import { revalidatePath } from 'next/cache';
export async function updateItem(formData) {
if (!supabase) {
return { error: 'Supabase client is not initialized. Cannot update item.' };
}
const id = formData.get('id');
if (!id) {
return { error: 'Item ID is required for updating.' };
}
// The picture_url is now received directly from the client
// after client-side upload to Supabase Storage if a new image was selected
const updatedItem = {
title: formData.get('title'),
type: formData.get('type'),
rating: formData.get('rating') ? parseInt(formData.get('rating'), 10) : null,
notes: formData.get('notes'),
picture_url: formData.get('picture_url'),
};
// Basic validation
if (!updatedItem.title || !updatedItem.type) {
return { error: 'Title and Type are required.' };
}
if (updatedItem.rating !== null && (updatedItem.rating < 1 || updatedItem.rating > 5)) {
return { error: 'Rating must be between 1 and 5.' };
}
try {
const { data, error } = await supabase
.from('items')
.update(updatedItem)
.eq('id', id)
.select(); // .select() to get the updated data back
if (error) {
console.error('Supabase update error:', error);
return { error: `Failed to update item: ${error.message}` };
}
console.log('Item updated successfully:', data);
revalidatePath('/'); // Revalidate the homepage to show the updated item
return {
success: true,
message: 'Item updated successfully!',
updatedItem: data ? data[0] : null
};
} catch (e) {
console.error('Error in updateItem action:', e);
return { error: 'An unexpected error occurred.' };
}
}

View File

@ -0,0 +1,325 @@
'use client';
import { useState, useEffect, useTransition, useRef } from 'react';
import { useRouter } from 'next/navigation';
import { supabase } from '@/lib/supabaseClient';
import { updateItem } from './actions';
export default function EditItemPage({ params }) {
const router = useRouter();
const { id } = params;
const formRef = useRef(null);
const [isPending, startTransition] = useTransition();
const [isLoading, setIsLoading] = useState(true);
const [isUploading, setIsUploading] = useState(false);
const [item, setItem] = useState(null);
const [error, setError] = useState(null);
const [successMessage, setSuccessMessage] = useState('');
// Fetch the item data
useEffect(() => {
async function fetchItem() {
setIsLoading(true);
setError(null);
if (!supabase) {
setError('Could not connect to the database.');
setIsLoading(false);
return;
}
try {
const { data, error } = await supabase
.from('items')
.select('*')
.eq('id', id)
.single();
if (error) {
throw error;
}
if (!data) {
throw new Error('Item not found');
}
setItem(data);
} catch (err) {
console.error('Error fetching item:', err);
setError(err.message || 'Failed to load item');
} finally {
setIsLoading(false);
}
}
if (id) {
fetchItem();
}
}, [id]);
const handleSubmit = async (event) => {
event.preventDefault();
setError(null);
setSuccessMessage('');
setIsUploading(true);
try {
const formData = new FormData(event.currentTarget);
const pictureFile = formData.get('picture_file');
let pictureUrl = item.picture_url; // Keep existing URL by default
// Handle image upload directly from client if a new 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('id', id);
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 updateItem(serverFormData);
if (result.error) {
setError(result.error);
} else if (result.success) {
setSuccessMessage(result.message);
// Redirect after a delay
setTimeout(() => router.push('/'), 1500);
}
});
} catch (err) {
setError(err.message);
} finally {
setIsUploading(false);
}
};
const handleDeleteClick = () => {
if (confirm('Are you sure you want to delete this item? This cannot be undone.')) {
startTransition(async () => {
try {
const { error } = await supabase
.from('items')
.delete()
.eq('id', id);
if (error) {
setError(`Failed to delete: ${error.message}`);
return;
}
setSuccessMessage('Item deleted successfully');
setTimeout(() => router.push('/'), 1500);
} catch (err) {
setError(err.message || 'Failed to delete item');
}
});
}
};
if (isLoading) {
return (
<div className="max-w-2xl mx-auto p-4 sm:p-6 lg:p-8 text-neutral-100">
<div className="text-center py-12">
<div className="animate-pulse flex flex-col items-center">
<div className="h-8 w-64 bg-neutral-700 rounded mb-4"></div>
<div className="h-4 w-48 bg-neutral-700 rounded"></div>
</div>
</div>
</div>
);
}
if (error && !item) {
return (
<div className="max-w-2xl mx-auto p-4 sm:p-6 lg:p-8 text-neutral-100">
<div className="bg-red-900 border border-red-700 text-red-100 p-4 rounded">
<h2 className="text-xl font-bold mb-2">Error</h2>
<p>{error}</p>
<button
onClick={() => router.push('/')}
className="mt-4 bg-neutral-800 hover:bg-neutral-700 text-white font-medium py-2 px-4 rounded transition-colors"
>
Go Back Home
</button>
</div>
</div>
);
}
return (
<div className="max-w-2xl mx-auto p-4 sm:p-6 lg:p-8 text-neutral-100">
<header className="mb-8">
<h1 className="text-3xl font-bold text-sky-400">Edit Item</h1>
<p className="text-neutral-400 mt-1">
Update information about "{item?.title || 'this item'}"
</p>
</header>
{error && (
<div className="mb-4 p-3 bg-red-900 border border-red-700 text-red-100 rounded">
<p className="font-semibold">Error:</p>
<p>{error}</p>
</div>
)}
{successMessage && (
<div className="mb-4 p-3 bg-green-900 border border-green-700 text-green-100 rounded">
<p className="font-semibold">Success:</p>
<p>{successMessage}</p>
</div>
)}
<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
type="text"
name="title"
id="title"
required
defaultValue={item?.title || ''}
className="block w-full bg-neutral-700 border-neutral-600 rounded-md shadow-sm py-2 px-3 text-neutral-100 focus:ring-sky-500 focus:border-sky-500 sm:text-sm"
placeholder="e.g., The Hitchhiker's Guide to the Galaxy"
/>
</div>
<div>
<label htmlFor="type" className="block text-sm font-medium text-neutral-300 mb-1">Type <span className="text-red-500">*</span></label>
<select
name="type"
id="type"
required
defaultValue={item?.type || ''}
className="block w-full bg-neutral-700 border-neutral-600 rounded-md shadow-sm py-2 px-3 text-neutral-100 focus:ring-sky-500 focus:border-sky-500 sm:text-sm"
>
<option value="">Select a type</option>
<option value="book">Book</option>
<option value="movie">Movie</option>
<option value="series">TV Series</option>
<option value="game">Game</option>
<option value="music">Music Album</option>
<option value="other">Other</option>
</select>
</div>
<div>
<label htmlFor="rating" className="block text-sm font-medium text-neutral-300 mb-1">Rating (1-5)</label>
<input
type="number"
name="rating"
id="rating"
min="1"
max="5"
defaultValue={item?.rating || ''}
className="block w-full bg-neutral-700 border-neutral-600 rounded-md shadow-sm py-2 px-3 text-neutral-100 focus:ring-sky-500 focus:border-sky-500 sm:text-sm"
placeholder="e.g., 5"
/>
</div>
<div>
<label htmlFor="picture_file" className="block text-sm font-medium text-neutral-300 mb-1">Picture</label>
{item?.picture_url && (
<div className="mb-2">
<p className="text-xs text-neutral-400 mb-2">Current image:</p>
<img
src={item.picture_url}
alt={item.title || 'Item image'}
className="h-32 object-cover rounded"
/>
<p className="text-xs text-neutral-500 mt-1">Upload a new image to replace the current one</p>
</div>
)}
<input
type="file"
name="picture_file"
id="picture_file"
accept="image/*"
className="block w-full text-sm text-neutral-400 file:mr-4 file:py-2 file:px-4 file:rounded-md file:border-0 file:text-sm file:font-semibold file:bg-sky-100 file:text-sky-700 hover:file:bg-sky-200 focus:outline-none focus:ring-2 focus:ring-sky-500 focus:border-sky-500"
/>
</div>
<div>
<label htmlFor="notes" className="block text-sm font-medium text-neutral-300 mb-1">Notes</label>
<textarea
name="notes"
id="notes"
rows="4"
defaultValue={item?.notes || ''}
className="block w-full bg-neutral-700 border-neutral-600 rounded-md shadow-sm py-2 px-3 text-neutral-100 focus:ring-sky-500 focus:border-sky-500 sm:text-sm"
placeholder="Why is this item your favorite? Any interesting thoughts?"
></textarea>
</div>
<div className="flex justify-between items-center pt-3">
<button
type="button"
onClick={handleDeleteClick}
disabled={isPending}
className="inline-flex items-center justify-center px-4 py-2 border border-transparent text-sm font-medium rounded-md text-white bg-red-600 hover:bg-red-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-offset-neutral-800 focus:ring-red-500 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
>
Delete Item
</button>
<div className="flex space-x-3">
<button
type="button"
onClick={() => router.push('/')}
disabled={isPending || isUploading}
className="inline-flex items-center justify-center px-4 py-2 border border-neutral-600 text-sm font-medium rounded-md text-neutral-200 bg-transparent hover:bg-neutral-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-offset-neutral-800 focus:ring-neutral-500 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
>
Cancel
</button>
<button
type="submit"
disabled={isPending || isUploading}
className="inline-flex items-center justify-center px-6 py-2 border border-transparent text-sm 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"
>
{isUploading ? 'Uploading Image...' : isPending ? 'Saving Changes...' : 'Save Changes'}
</button>
</div>
</div>
</form>
</div>
);
}

View File

@ -1,5 +1,7 @@
import { supabase, safeQuery } from '../lib/supabaseClient';
import Link from 'next/link';
// Function to generate star ratings
const StarRating = ({ rating }) => {
const totalStars = 5;
@ -65,7 +67,11 @@ export default async function Home() {
{items.length > 0 && (
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6">
{items.map((item) => (
<div key={item.id} className="bg-neutral-800 rounded-lg shadow-lg p-4 flex flex-col">
<Link
href={`/edit-item/${item.id}`}
key={item.id}
className="bg-neutral-800 rounded-lg shadow-lg p-4 flex flex-col hover:bg-neutral-700/50 hover:shadow-xl transform hover:-translate-y-1 transition-all duration-200 cursor-pointer group"
>
{item.picture_url ? (
<div className="aspect-[3/4] w-full bg-neutral-700 rounded mb-3 overflow-hidden">
<img
@ -75,11 +81,11 @@ export default async function Home() {
/>
</div>
) : (
<div className="aspect-[3/4] w-full bg-neutral-700 rounded mb-3 flex items-center justify-center">
<div className="aspect-[3/4] w-full bg-neutral-700 rounded mb-3 flex items-center justify-center group-hover:bg-neutral-600 transition-colors">
<span className="text-neutral-500 text-sm">No Image</span>
</div>
)}
<h2 className="text-xl font-semibold mb-1 text-neutral-100 truncate" title={item.title}>{item.title || 'Untitled'}</h2>
<h2 className="text-xl font-semibold mb-1 text-neutral-100 truncate group-hover:text-sky-300 transition-colors" title={item.title}>{item.title || 'Untitled'}</h2>
<p className="text-sm text-neutral-400 mb-1 capitalize">{item.type || 'N/A'}</p>
{typeof item.rating === 'number' && <StarRating rating={item.rating} />}
{item.notes && (
@ -87,11 +93,13 @@ export default async function Home() {
{item.notes}
</p>
)}
{/* Placeholder for a details link/modal trigger */}
{/* <a href={`/item/${item.id}`} className="text-sky-400 hover:text-sky-300 text-sm mt-auto pt-2">
View Details
</a> */}
</div>
<div className="mt-3 text-xs text-sky-400 group-hover:text-sky-300 flex items-center transition-colors">
<span>Edit Item</span>
<svg xmlns="http://www.w3.org/2000/svg" className="h-3 w-3 ml-1" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5l7 7-7 7" />
</svg>
</div>
</Link>
))}
</div>
)}