imma send you two codes, first one is recipe page client and i want you to use the way…
- User
imma send you two codes, first one is recipe page client and i want you to use the way it records the recipe details and and do something similar to the secon code which is update recipe, it should inclue all fields as shown but with each field filled with the details from the recipe records
- Assistant
Sure! Please provide the two code samples (the recipe page client and the update recipe code), and I'll help you modify the update recipe code to include the details from the recipe records while maintaining the structure of the first recipe page client.
- User
'use client';
import { useEffect, useState } from 'react'; import { useForm, useFieldArray, Controller } from 'react-hook-form'; import { TextInput, Textarea, NumberInput, Switch, Button, MultiSelect, Loader, } from '@mantine/core'; import Link from 'next/link'; import { useUpdateRecipe } from '@/hooks/useUpdateRecipe'; import { useFetchAll } from '@/hooks/useFetchAll'; import { useRouter, useSearchParams } from 'next/navigation'; import { uploadImages, insertRecipeCategories, deleteRecipeCategories, fetch, fetchAll, } from '@/services/supabase_service'; import { Json } from '@/models/json';
interface Ingredient { name: string; amount: number; unit: string; }
interface DirectionStep { instruction: string; }
export interface RecipeFormValues { user_id: string; name: string; description?: string; prep_time: number; cook_time?: number; servings?: number; shared?: boolean; ingredients: Ingredient[]; directions: DirectionStep[]; images: FileList | null; videos: null; categories: number[]; // Selected category IDs from join table. }
function UpdateRecipeClient() { const searchParams = useSearchParams(); const recipeId = searchParams.get('id') || ''; const router = useRouter();
const { register, handleSubmit, control, reset } = useForm({ defaultValues: { // TODO - Add user_id from auth user_id: '', name: '', description: '', prep_time: 0, cook_time: 0, servings: 0, shared: false, ingredients: [{ name: '', amount: 0, unit: '' }], directions: [{ instruction: '' }], images: null, videos: null, categories: [], }, }); const [initialCategories, setInitialCategories] = useState<number[]>([]); const [isRecipeLoading, setIsRecipeLoading] = useState(true);
const { fields: ingredientFields, append: appendIngredient, remove: removeIngredient, } = useFieldArray({ control, name: 'ingredients' }); const { fields: directionFields, append: appendDirection, remove: removeDirection, } = useFieldArray({ control, name: 'directions' });
// Fetch all categories for MultiSelect const { data: categoriesData, isLoading: categoriesLoading } = useFetchAll({ table: 'categories', usePagination: false, }); const categoryOptions = (categoriesData?.data as { id: number; name: string }[] | undefined)?.map( (cat) => ({ value: cat.id.toString(), label: cat.name, }), ) || [];
const { mutateAsync, isPending } = useUpdateRecipe();
// Fetch the recipe record using fetch, // then use fetchAll on 'recipe_categories' to get its associated categories. useEffect(() => { if (recipeId) { fetch('recipes', recipeId) .then(async (recipeData) => { // Use fetchAll with a filter on recipe_categories to get associated category IDs. const catResult = await fetchAll({ table: 'recipe_categories', filters: [{ column: 'recipe_id', value: recipeId, operator: 'eq' }], usePagination: false, }); const recipeCategories = catResult.data.map((row) => row.category_id); const completeData = { ...recipeData, categories: recipeCategories || [], }; reset(completeData); setInitialCategories(completeData.categories); setIsRecipeLoading(false); }) .catch((error) => { console.error('Error fetching recipe:', error); alert('Failed to load recipe for editing'); setIsRecipeLoading(false); }); } }, [recipeId, reset]);
const onSubmit = async (values: RecipeFormValues) => { let imageUrls: string[] | null = null; if (values.images && values.images.length > 0) { const filesArray = Array.from(values.images); try { imageUrls = await uploadImages(filesArray); } catch (error) { alert('Image upload failed'); console.error(error); return; } }
// Exclude categories from the update payload. const { categories, ...recipeData } = values; const computedTotalTime = values.prep_time + (values.cook_time ?? 0); const updatePayload = { ...recipeData, total_time: computedTotalTime, ingredients: values.ingredients as unknown as Json, directions: values.directions as unknown as Json, images: imageUrls, }; try { const updatedData = await mutateAsync({ recipeId, data: updatePayload }); const updatedRecipe = Array.isArray(updatedData) ? updatedData[0] : updatedData; // Differential update for join records: const newCategories = categories; const categoriesToAdd = newCategories.filter( (cat) => !initialCategories.includes(cat), ); const categoriesToRemove = initialCategories.filter( (cat) => !newCategories.includes(cat), ); if (updatedRecipe?.id) { if (categoriesToRemove.length > 0) { await deleteRecipeCategories(updatedRecipe.id, categoriesToRemove); } if (categoriesToAdd.length > 0) { await insertRecipeCategories(updatedRecipe.id, categoriesToAdd); } } reset(); router.push('/supabase'); } catch (error) { console.error('Error updating recipe or categories:', error); alert('Failed to update recipe'); }};
if (isRecipeLoading) { return ( ); }
return ( Back Update Recipe <TextInput label='Recipe Name' placeholder='Enter recipe name' {...register('name', { required: true })} required variant='filled' className='w-full' /> <Textarea label='Description' placeholder='Enter recipe description' {...register('description')} variant='filled' className='w-full' /> <Controller control={control} name='prep_time' rules={{ required: true }} render={({ field: { value, onChange } }) => ( )} /> <Controller control={control} name='cook_time' render={({ field: { value, onChange } }) => ( )} /> <Controller control={control} name='servings' render={({ field: { value, onChange } }) => ( )} /> <Controller control={control} name='shared' render={({ field }) => ( <Switch label='Shared' checked={field.value} onChange={(event) => field.onChange(event.currentTarget.checked)} color='blue' /> )} />
{/* MultiSelect for Categories */} <Controller control={control} name='categories' render={({ field }) => ( <MultiSelect label='Categories' placeholder={ categoriesLoading ? 'Loading categories...' : 'Select categories' } data={categoryOptions} value={field.value.map(String)} onChange={(values) => field.onChange(values.map(Number))} searchable nothingFoundMessage='No categories found' className='w-full' disabled={categoriesLoading} /> )} /> {/* Label and File input for images */} <div className='flex flex-col'> <label className='mb-1 font-medium'>Recipe Images</label> <Controller control={control} name='images' render={({ field: { onChange, ref } }) => ( <input type='file' multiple accept='image/*' onChange={(e) => onChange(e.target.files)} ref={ref} title='Upload Images' className='block w-full text-sm text-gray-500 file:mr-4 file:py-2 file:px-4 file:rounded file:border-0 file:text-sm file:font-semibold file:bg-blue-50 file:text-blue-700 hover:file:bg-blue-100' /> )} /> </div> {/* Structured Ingredients */} <div className='border p-4 rounded'> <h3 className='font-bold mb-2'>Ingredients</h3> {ingredientFields.map((field, index) => ( <div key={field.id} className='flex gap-2 mb-2' > <TextInput placeholder='Name' {...register(`ingredients.${index}.name` as const, { required: true, })} className='flex-1' /> <Controller control={control} name={`ingredients.${index}.amount` as const} rules={{ required: true }} render={({ field: { value, onChange } }) => ( <NumberInput placeholder='Amount' value={value} onChange={onChange} className='w-24' /> )} /> <TextInput placeholder='Unit' {...register(`ingredients.${index}.unit` as const, { required: true, })} className='w-24' /> <Button color='red' onClick={() => removeIngredient(index)} > Remove </Button> </div> ))} <Button color='blue' onClick={() => appendIngredient({ name: '', amount: 0, unit: '' })} > Add Ingredient </Button> </div> {/* Structured Directions */} <div className='border p-4 rounded'> <h3 className='font-bold mb-2'>Directions</h3> {directionFields.map((field, index) => ( <div key={field.id} className='flex gap-2 mb-2' > <Textarea placeholder={`Step ${index + 1}`} {...register(`directions.${index}.instruction` as const, { required: true, })} className='flex-1' /> <Button color='red' onClick={() => removeDirection(index)} > Remove </Button> </div> ))} <Button color='blue' onClick={() => appendDirection({ instruction: '' })} > Add Direction </Button> </div> <Button type='submit' loading={isPending} color='blue' className='w-full' > Update Recipe </Button> </form> </div>); }
export default UpdateRecipeClient;
this is the first code
- Assistant
Thank you for providing the recipe page client code. Please provide the second code (the update recipe code), and I'll assist you in making the necessary adjustments to include the recipe details in the update recipe logic.
- User
'use client';
import React, { useEffect, useState } from 'react'; import { useSearchParams } from 'next/navigation'; import { Icon } from '@iconify/react'; import CustomAppShell from '@/components/customAppShell/customAppShell'; import CustomBadge from '@/components/customBadge/customBadge'; import IngredientCard from '@/components/ingredientCard/ingredientCard'; import NotesCard from '@/components/notesCard/notesCard'; import CustomImage from '@/components/customImage/customImage'; import IconCard from '@/components/iconCard/iconCard'; import { fetch, fetchAll } from '@/services/supabase_service'; import { RecipeRecord } from '@/services/supabase_service'; import DirectionsCard from '@/components/directionsCard/directionsCard'; import AuthenticatedPage from '@/components/authenticated_page/authenticated_page'; import Link from 'next/link';
function RecipePageClient() { const searchParams = useSearchParams(); const recipeId = searchParams.get('id') || ''; const [recipe, setRecipe] = useState<RecipeRecord | null>(null); const [isLoading, setIsLoading] = useState(true); const [recipeCategories, setRecipeCategories] = useState<string[]>([]); const [catLoading, setCatLoading] = useState(true);
useEffect(() => { if (recipeId) { // Fetch the recipe data fetch('recipes', recipeId) .then((data) => { setRecipe(data); // After recipe is fetched, fetch its categories fetchAll({ table: 'recipe_categories', filters: [{ column: 'recipe_id', value: recipeId, operator: 'eq' }], usePagination: false, }) .then((rcResult) => { type RecipeCategory = { recipe_id: string; category_id: number }; const categoryIds = (rcResult.data as RecipeCategory[]).map( (rc) => rc.category_id, ); if (categoryIds.length > 0) { // Fetch the actual category names fetchAll({ table: 'categories', filters: [ { column: 'id', value: categoryIds, operator: 'in' }, ], usePagination: false, }) .then((catResult) => { type Category = { id: number; name: string }; const names = (catResult.data as Category[]).map( (cat) => cat.name, ); setRecipeCategories(names); setCatLoading(false); }) .catch((err) => { console.error('Error fetching categories:', err); setCatLoading(false); }); } else { setRecipeCategories([]); setCatLoading(false); } }) .catch((err) => { console.error('Error fetching recipe categories:', err); setCatLoading(false); }); setIsLoading(false); }) .catch((error) => { console.error('Error fetching recipe:', error); setIsLoading(false); }); } }, [recipeId]);
// TODO - Change to Loader if (isLoading) { return ( Loading... ); }
if (!recipe) { return ( Recipe not found. ); }
// Process image source const imageSrc = typeof recipe.images === 'string' ? recipe.images : Array.isArray(recipe.images) && recipe.images.length > 0 && typeof recipe.images[0] === 'object' && recipe.images[0] !== null && 'image' in recipe.images[0] ? (recipe.images[0] as { image: string }).image : 'https://raw.githubusercontent.com/mantinedev/mantine/master/.demo/images/bg-7.png';
// Ensure ingredients, directions, and notes are parsed const ingredients = typeof recipe.ingredients === 'string' ? JSON.parse(recipe.ingredients) : recipe.ingredients; const directions = typeof recipe.directions === 'string' ? JSON.parse(recipe.directions) : recipe.directions; const notes = typeof recipe.notes === 'string' ? JSON.parse(recipe.notes) : recipe.notes || [];
return ( {recipe.name} <Link className='px-4 h-8 flex bg-gray-300 items-center border-black rounded-full hover:bg-gray-400' href={'/update_recipe'} > Edit {recipe.user_id} {!catLoading ? ( recipeCategories.length > 0 ? ( recipeCategories.map((catName, idx) => ( )) ) : null ) : ( Loading categories... )} <IconCard label='Prep Time' subText={
${recipe.prep_time} min} bgColor='bg-green-200' labelColor='text-slate-700' subTextColor='text-slate-900' /> <IconCard label='Cook Time' subText={recipe.cook_time ?${recipe.cook_time} min: 'N/A'} bgColor='bg-green-200' labelColor='text-slate-700' subTextColor='text-slate-900' /> {ingredients.length > 0 && } {notes.length > 0 && } {directions.length > 0 && } ); }export default RecipePageClient; and the second code
- Assistant
Thank you for providing both pieces of code. Based on the
UpdateRecipeClientcomponent in the first code you shared and theRecipePageClientcomponent from the second code, I can help you create an update recipe form filled with details from the recipe as fetched in the recipe page.Here’s how the
UpdateRecipeClientcan be adjusted to prefill the fields with the recipe details fetched in theRecipePageClient. I’ll ensure that all the necessary details are included in the form:Modified UpdateRecipeClient Component
'use client'; import { useEffect, useState } from 'react'; import { useForm, useFieldArray, Controller } from 'react-hook-form'; import { TextInput, Textarea, NumberInput, Switch, Button, MultiSelect, Loader, } from '@mantine/core'; import Link from 'next/link'; import { useUpdateRecipe } from '@/hooks/useUpdateRecipe'; import { useFetchAll } from '@/hooks/useFetchAll'; import { useRouter, useSearchParams } from 'next/navigation'; import { uploadImages, insertRecipeCategories, deleteRecipeCategories, fetch, fetchAll, } from '@/services/supabase_service'; import { Json } from '@/models/json'; // Interface definitions (same as before...) interface Ingredient { name: string; amount: number; unit: string; } interface DirectionStep { instruction: string; } export interface RecipeFormValues { user_id: string; name: string; description?: string; prep_time: number; cook_time?: number; servings?: number; shared?: boolean; ingredients: Ingredient[]; directions: DirectionStep[]; images: FileList | null; videos: null; categories: number[]; } function UpdateRecipeClient() { const searchParams = useSearchParams(); const recipeId = searchParams.get('id') || ''; const router = useRouter(); const { register, handleSubmit, control, reset } = useForm<RecipeFormValues>({ defaultValues: { user_id: '', name: '', description: '', prep_time: 0, cook_time: 0, servings: 0, shared: false, ingredients: [{ name: '', amount: 0, unit: '' }], directions: [{ instruction: '' }], images: null, videos: null, categories: [], }, }); const [initialCategories, setInitialCategories] = useState<number[]>([]); const [isRecipeLoading, setIsRecipeLoading] = useState<boolean>(true); const { fields: ingredientFields, append: appendIngredient, remove: removeIngredient, } = useFieldArray({ control, name: 'ingredients' }); const { fields: directionFields, append: appendDirection, remove: removeDirection, } = useFieldArray({ control, name: 'directions' }); const { data: categoriesData, isLoading: categoriesLoading } = useFetchAll({ table: 'categories', usePagination: false, }); const categoryOptions = (categoriesData?.data as { id: number; name: string }[] | undefined)?.map( (cat) => ({ value: cat.id.toString(), label: cat.name, }), ) || []; const { mutateAsync, isPending } = useUpdateRecipe(); useEffect(() => { if (recipeId) { fetch<RecipeFormValues>('recipes', recipeId) .then(async (recipeData) => { const catResult = await fetchAll({ table: 'recipe_categories', filters: [{ column: 'recipe_id', value: recipeId, operator: 'eq' }], usePagination: false, }); const recipeCategories = catResult.data.map((row) => row.category_id); const completeData = { ...recipeData, categories: recipeCategories || [], }; reset(completeData); setInitialCategories(completeData.categories); setIsRecipeLoading(false); }) .catch((error) => { console.error('Error fetching recipe:', error); alert('Failed to load recipe for editing'); setIsRecipeLoading(false); }); } }, [recipeId, reset]); const onSubmit = async (values: RecipeFormValues) => { let imageUrls: string[] | null = null; if (values.images && values.images.length > 0) { const filesArray = Array.from(values.images); try { imageUrls = await uploadImages(filesArray); } catch (error) { alert('Image upload failed'); console.error(error); return; } } const { categories, ...recipeData } = values; const computedTotalTime = values.prep_time + (values.cook_time ?? 0); const updatePayload = { ...recipeData, total_time: computedTotalTime, ingredients: values.ingredients as unknown as Json, directions: values.directions as unknown as Json, images: imageUrls, }; try { const updatedData = await mutateAsync({ recipeId, data: updatePayload }); const updatedRecipe = Array.isArray(updatedData) ? updatedData[0] : updatedData; // Update the categories in the database const newCategories = categories; const categoriesToAdd = newCategories.filter((cat) => !initialCategories.includes(cat)); const categoriesToRemove = initialCategories.filter((cat) => !newCategories.includes(cat)); if (updatedRecipe?.id) { if (categoriesToRemove.length > 0) { await deleteRecipeCategories(updatedRecipe.id, categoriesToRemove); } if (categoriesToAdd.length > 0) { await insertRecipeCategories(updatedRecipe.id, categoriesToAdd); } } reset(); router.push('/supabase'); } catch (error) { console.error('Error updating recipe or categories:', error); alert('Failed to update recipe'); } }; if (isRecipeLoading) { return ( <div className='max-w-3xl min-h-96 mx-auto mt-10 p-6 bg-gray-900 text-white rounded shadow flex items-center justify-center'> <Loader color='blue' size='lg' /> </div> ); } return ( <div className='max-w-3xl mx-auto mt-10 p-6 bg-gray-900 text-white rounded shadow'> <div className='flex justify-between items-center mb-6'> <Button component={Link} href='/supabase' variant='outline' color='blue'> Back </Button> <h2 className='text-2xl font-bold text-center flex-1'>Update Recipe</h2> </div> <form onSubmit={handleSubmit(onSubmit)} className='space-y-4'> <TextInput label='Recipe Name' placeholder='Enter recipe name' {...register('name', { required: true })} required variant='filled' className='w-full' /> <Textarea label='Description' placeholder='Enter recipe description' {...register('description')} variant='filled' className='w-full' /> <Controller control={control} name='prep_time' rules={{ required: true }} render={({ field: { value, onChange } }) => ( <NumberInput label='Prep Time (minutes)' placeholder='Prep time' value={value} onChange={onChange} required variant='filled' className='w-full' /> )} /> <Controller control={control} name='cook_time' render={({ field: { value, onChange } }) => ( <NumberInput label='Cook Time (minutes)' placeholder='Cook time' value={value} onChange={onChange} variant='filled' className='w-full' /> )} /> <Controller control={control} name='servings' render={({ field: { value, onChange } }) => ( <NumberInput label='Servings' placeholder='Servings' value={value} onChange={onChange} variant='filled' className='w-full' /> )} /> <Controller control={control} name='shared' render={({ field }) => ( <Switch label='Shared' checked={field.value} onChange={(event) => field.onChange(event.currentTarget.checked)} color='blue' /> )} /> <Controller control={control} name='categories' render={({ field }) => ( <MultiSelect label='Categories' placeholder={categoriesLoading ? 'Loading categories...' : 'Select categories'} data={categoryOptions} value={field.value.map(String)} onChange={(values) => field.onChange(values.map(Number))} searchable nothingFoundMessage='No categories found' className='w-full' disabled={categoriesLoading} /> )} /> <div className='flex flex-col'> <label className='mb-1 font-medium'>Recipe Images</label> <Controller control={control} name='images' render={({ field: { onChange, ref } }) => ( <input type='file' multiple accept='image/*' onChange={(e) => onChange(e.target.files)} ref={ref} title='Upload Images' className='block w-full text-sm text-gray-500 file:mr-4 file:py-2 file:px-4 file:rounded file:border-0 file:text-sm file:font-semibold file:bg-blue-50 file:text-blue-700 hover:file:bg-blue-100' /> )} /> </div> <div className='border p-4 rounded'> <h3 className='font-bold mb-2'>Ingredients</h3> {ingredientFields.map((field, index) => ( <div key={field.id} className='flex gap-2 mb-2'> <TextInput placeholder='Name' {...register(`ingredients.${index}.name` as const, { required: true })} className='flex-1' /> <Controller control={control} name={`ingredients.${index}.amount` as const} rules={{ required: true }} render={({ field: { value, onChange } }) => ( <NumberInput placeholder='Amount' value={value} onChange={onChange} className='w-24' /> )} /> <TextInput placeholder='Unit' {...register(`ingredients.${index}.unit` as const, { required: true })} className='w-24' /> <Button color='red' onClick={() => removeIngredient(index)}>Remove</Button> </div> ))} <Button color='blue' onClick={() => appendIngredient({ name: '', amount: 0, unit: '' })}>Add Ingredient</Button> </div> <div className='border p-4 rounded'> <h3 className='font-bold mb-2'>Directions</h3> {directionFields.map((field, index) => ( <div key={field.id} className='flex gap-2 mb-2'> <Textarea placeholder={`Step ${index + 1}`} {...register(`directions.${index}.instruction` as const, { required: true })} className='flex-1' /> <Button color='red' onClick={() => removeDirection(index)}>Remove</Button> </div> ))} <Button color='blue' onClick={() => appendDirection({ instruction: '' })}>Add Direction</Button> </div> <Button type='submit' loading={isPending} color='blue' className='w-full'>Update Recipe</Button> </form> </div> ); } export default UpdateRecipeClient;Key Changes and Additions:
-
Recipe Data Fetching: The
useEffecthook fetches recipe details upon mounting, similar to how it's done in theRecipePageClient. This also includes fetching its associated categories. -
Form Management: Fields like
ingredients,directions, etc. are populated using values fetched from the database. Theresetfunction fromreact-hook-formis used to prepopulate the form. -
Submit Logic: Includes logic to handle image uploads and updates to aligned categories.
-
Loading States: Displays a loading spinner while fetching data to improve user experience.
-
Error Handling: Alerts and logging included to better handle fetch errors.
By implementing these refinements, the
UpdateRecipeClientcomponent will behave similarly to theRecipePageClient, but with a focus on updating the recipe based on the user inputs. Let me know if you need any further modifications or explanations! -
- User
use the recipePageClient to extract recipe details to fill in these fields in this code 'use client';
import { useForm, useFieldArray, Controller } from 'react-hook-form'; import { TextInput, Textarea, NumberInput, Switch, Button, MultiSelect, } from '@mantine/core'; import Link from 'next/link'; import { useRouter } from 'next/navigation'; import { useState } from 'react'; import { useInsertRecipe } from '@/hooks/useInsertRecipe'; import { useFetchAll } from '@/hooks/useFetchAll'; import { uploadImages, insertRecipeCategories, } from '@/services/supabase_service'; import { Json } from '@/models/json'; import AuthenticatedPage from '@/components/authenticated_page/authenticated_page'; // import { useAuthStore } from '@/stores/auth_store';
interface Ingredient { name: string; amount: number; unit: string; }
interface DirectionStep { instruction: string; }
interface Note { note: string; }
interface RecipeFormValues { user_id: string; name: string; difficulty: number; prep_time: number; cook_time?: number; servings?: number; shared?: boolean; ingredients: Ingredient[]; directions: DirectionStep[]; notes?: Note[] | null; images: FileList | null; videos: null; categories: number[]; // Selected category IDs (for join table) }
function UpdateRecipeClient() { // const { session } = useAuthStore(); // const userId = session?.user?.id ?? '';
// console.log('userId:', userId);
const { register, handleSubmit, control, reset, setValue } = useForm({ defaultValues: { // TODO: Use a valid user_id from your auth.users table. user_id: process.env.NEXT_PUBLIC_TEST_USER_ID ?? '', // user_id: userId, name: '', difficulty: 0, prep_time: 0, cook_time: 0, servings: 0, shared: false, ingredients: [{ name: '', amount: 0, unit: '' }], directions: [{ instruction: '' }], notes: null, images: null, videos: null, categories: [], }, mode: 'onChange', });
// Field arrays for structured fields const { fields: ingredientFields, append: appendIngredient, remove: removeIngredient, } = useFieldArray({ control, name: 'ingredients', });
const { fields: directionFields, append: appendDirection, remove: removeDirection, } = useFieldArray({ control, name: 'directions', });
const { fields: noteFields, append: appendNote, remove: removeNote, } = useFieldArray({ control, name: 'notes', });
// Fetch categories using useFetchAll (table: 'categories') with pagination disabled. const { data: categoriesData, isLoading: categoriesLoading } = useFetchAll({ table: 'categories', usePagination: false, });
const categoryOptions = (categoriesData?.data as { id: number; name: string }[] | undefined)?.map( (cat) => ({ value: cat.id.toString(), label: cat.name, }), ) || [];
const [difficulty, setDifficulty] = useState(0); const handleDifficultyChange = (value: number) => { setDifficulty(value); setValue('difficulty', value); };
const { mutateAsync, isPending } = useInsertRecipe(); const router = useRouter();
const onSubmit = async (values: RecipeFormValues) => { // Process image uploads if files are selected. let imageUrls: string[] | null = null; if (values.images && values.images.length > 0) { const filesArray = Array.from(values.images); try { imageUrls = await uploadImages(filesArray); } catch (error) { alert('Image upload failed'); console.error(error); return; } }
// Extract categories separately so they're not part of the payload. const { categories, ...recipeData } = values; // Auto-calculate total_time as prep_time + cook_time (default cook_time to 0 if undefined) const computedTotalTime = values.prep_time + (values.cook_time ?? 0); const recipePayload = { ...recipeData, total_time: computedTotalTime, ingredients: values.ingredients as unknown as Json, directions: values.directions as unknown as Json, notes: values.notes as unknown as Json, images: imageUrls, }; try { const recipeDataResponse = await mutateAsync(recipePayload); // Assume the inserted recipe is returned as an array. const newRecipe = Array.isArray(recipeDataResponse) ? recipeDataResponse[0] : recipeDataResponse; if (categories.length > 0 && newRecipe?.id) { await insertRecipeCategories(newRecipe.id, categories); } reset(); router.push(`/recipe_page?id=${newRecipe?.id}`); } catch (error) { console.error('Error inserting recipe or categories:', error); alert('Failed to insert recipe'); }};
return ( Back Insert Recipe <TextInput label='Recipe Name' placeholder='Enter recipe name' {...register('name', { required: true })} required variant='filled' className='w-full' /> {/* Difficulty Section /} Difficulty <button type='button' className={
flex-1 py-2 rounded-md text-black ${ difficulty === 0 ? 'bg-violet-300' : 'border bg-slate-200 hover:bg-slate-300' }} onClick={() => handleDifficultyChange(0)} > Easy <button type='button' className={flex-1 py-2 rounded-md text-black ${ difficulty === 1 ? 'bg-violet-300' : 'border bg-slate-200 hover:bg-slate-300' }} onClick={() => handleDifficultyChange(1)} > Medium <button type='button' className={flex-1 py-2 rounded-md text-black ${ difficulty === 2 ? 'bg-violet-300' : 'border bg-slate-200 hover:bg-slate-300' }} onClick={() => handleDifficultyChange(2)} > Hard <input type='hidden' {...register('difficulty')} value={difficulty} /> <Controller control={control} name='prep_time' rules={{ required: true }} render={({ field: { value, onChange } }) => ( )} /> <Controller control={control} name='cook_time' render={({ field: { value, onChange } }) => ( )} /> <Controller control={control} name='servings' render={({ field: { value, onChange } }) => ( )} /> <Controller control={control} name='shared' render={({ field }) => ( <Switch label='Shared' checked={field.value} onChange={(event) => field.onChange(event.currentTarget.checked) } color={'#DBCDF0'} /> )} /> {/ MultiSelect for Categories /} <Controller control={control} name='categories' render={({ field }) => ( <MultiSelect label='Categories' placeholder={ categoriesLoading ? 'Loading categories...' : 'Select categories' } data={categoryOptions} value={field.value.map(String)} onChange={(values) => field.onChange(values.map(Number))} searchable nothingFoundMessage='No categories found' className='w-full' disabled={categoriesLoading} /> )} /> {/ Label and File input for images /} Recipe Images <Controller control={control} name='images' render={({ field: { onChange, ref } }) => ( <input type='file' multiple accept='image/' onChange={(e) => onChange(e.target.files)} ref={ref} title='Upload Images' className='block w-full text-sm text-gray-500 file:mr-4 file:py-2 file:px-4 file:rounded file:border-0 file:text-sm file:font-semibold file:bg-violet-200 file:text-gray-800 hover:file:bg-violet-100' /> )} /> {/* Structured Ingredients /} Ingredients {ingredientFields.map((field, index) => ( <TextInput placeholder='Name' {...register(ingredients.${index}.nameas const, { required: true, })} className='flex-1' /> <Controller control={control} name={ingredients.${index}.amountas const} rules={{ required: true }} render={({ field: { value, onChange } }) => ( )} /> <TextInput placeholder='Unit' {...register(ingredients.${index}.unitas const, { required: true, })} className='w-24' /> <Button color='red' onClick={() => removeIngredient(index)} > Remove ))} <button type='button' className='bg-slate-200 text-black rounded-md hover:bg-slate-100 transition-all flex items-center justify-center px-4 h-10' onClick={() => appendIngredient({ name: '', amount: 0, unit: '' }) } > Add Ingredient {/ Structured Directions /} Directions {directionFields.map((field, index) => ( <Textarea placeholder={Step ${index + 1}} {...register(directions.${index}.instructionas const, { required: true, })} className='flex-1' /> <Button color='red' onClick={() => removeDirection(index)} > Remove ))} <button type='button' className='bg-slate-200 text-black rounded-md hover:bg-slate-100 transition-all flex items-center justify-center px-4 h-10' onClick={() => appendDirection({ instruction: '' })} > Add Direction {/ Structured Notes */} Notes {noteFields.map((field, index) => ( <Textarea placeholder={Note ${index + 1}} {...register(notes.${index}.noteas const, { required: true, })} className='flex-1' /> <Button color='red' onClick={() => removeNote(index)} > Remove ))} <button type='button' className='bg-slate-200 text-black rounded-md hover:bg-slate-100 transition-all flex items-center justify-center px-4 h-10' onClick={() => appendNote({ note: '' })} > Add Note <button type='submit' className={rounded-xl transition-colors flex items-center justify-center text-sm h-10 w-full px-4 bg-violet-300 text-black ${ isPending ? 'opacity-50 cursor-not-allowed' : 'hover:bg-white hover:border hover:border-violet-400' }} // Handle loading state disabled={isPending} // Disable button when loading > {isPending ? 'Loading...' : 'Insert Recipe'} ); }export default UpdateRecipeClient;
- Assistant
To fill in the form fields in your
UpdateRecipeClientcomponent using the recipe details from theRecipePageClient, you first need to extract the relevant details when fetching the recipe data. Here’s how you can adjust yourUpdateRecipeClientcomponent to incorporate those recipe details.Updated
UpdateRecipeClientComponentThis version will include a useEffect call to fetch the recipe data by ID. It will fill in the form based on those details:
'use client'; import { useForm, useFieldArray, Controller } from 'react-hook-form'; import { TextInput, Textarea, NumberInput, Switch, Button, MultiSelect, Loader, } from '@mantine/core'; import Link from 'next/link'; import { useRouter, useSearchParams } from 'next/navigation'; import { useEffect, useState } from 'react'; // Import useEffect and useState import { useInsertRecipe } from '@/hooks/useInsertRecipe'; import { useFetchAll } from '@/hooks/useFetchAll'; import { uploadImages, insertRecipeCategories, fetch, fetchAll, } from '@/services/supabase_service'; import { Json } from '@/models/json'; import AuthenticatedPage from '@/components/authenticated_page/authenticated_page'; interface Ingredient { name: string; amount: number; unit: string; } interface DirectionStep { instruction: string; } interface Note { note: string; } interface RecipeFormValues { user_id: string; name: string; difficulty: number; prep_time: number; cook_time?: number; servings?: number; shared?: boolean; ingredients: Ingredient[]; directions: DirectionStep[]; notes?: Note[] | null; images: FileList | null; videos: null; categories: number[]; // Selected category IDs (for join table) } function UpdateRecipeClient() { const searchParams = useSearchParams(); const recipeId = searchParams.get('id') || ''; const router = useRouter(); const { register, handleSubmit, control, reset, setValue } = useForm<RecipeFormValues>({ defaultValues: { user_id: '', // Set this dynamically from your user auth context/store. name: '', difficulty: 0, prep_time: 0, cook_time: 0, servings: 0, shared: false, ingredients: [{ name: '', amount: 0, unit: '' }], directions: [{ instruction: '' }], notes: null, images: null, videos: null, categories: [], }, mode: 'onChange', }); // Field arrays for structured fields const { fields: ingredientFields, append: appendIngredient, remove: removeIngredient, } = useFieldArray({ control, name: 'ingredients', }); const { fields: directionFields, append: appendDirection, remove: removeDirection, } = useFieldArray({ control, name: 'directions', }); const { fields: noteFields, append: appendNote, remove: removeNote, } = useFieldArray({ control, name: 'notes', }); // Fetch categories using useFetchAll (table: 'categories') with pagination disabled. const { data: categoriesData, isLoading: categoriesLoading } = useFetchAll({ table: 'categories', usePagination: false, }); const categoryOptions = (categoriesData?.data as { id: number; name: string }[] | undefined)?.map( (cat) => ({ value: cat.id.toString(), label: cat.name, }), ) || []; const { mutateAsync, isPending } = useInsertRecipe(); // Fetch the recipe details to pre-fill the form useEffect(() => { if (recipeId) { fetch<RecipeFormValues>('recipes', recipeId) .then(async (recipeData) => { // Fetch associated categories const catResult = await fetchAll({ table: 'recipe_categories', filters: [{ column: 'recipe_id', value: recipeId, operator: 'eq' }], usePagination: false, }); const recipeCategories = catResult.data.map((row) => row.category_id); const completeData = { ...recipeData, categories: recipeCategories || [], }; // Use reset to fill in the form reset(completeData); }) .catch((error) => { console.error('Error fetching recipe:', error); alert('Failed to load recipe for editing'); }); } }, [recipeId, reset]); const onSubmit = async (values: RecipeFormValues) => { // Process image uploads if files are selected. let imageUrls: string[] | null = null; if (values.images && values.images.length > 0) { const filesArray = Array.from(values.images); try { imageUrls = await uploadImages(filesArray); } catch (error) { alert('Image upload failed'); console.error(error); return; } } const { categories, ...recipeData } = values; // Auto-calculate total_time as prep_time + cook_time (default cook_time to 0 if undefined) const computedTotalTime = values.prep_time + (values.cook_time ?? 0); const recipePayload = { ...recipeData, total_time: computedTotalTime, ingredients: values.ingredients as unknown as Json, directions: values.directions as unknown as Json, notes: values.notes as unknown as Json, images: imageUrls, }; try { const recipeDataResponse = await mutateAsync(recipePayload); const newRecipe = Array.isArray(recipeDataResponse) ? recipeDataResponse[0] : recipeDataResponse; if (categories.length > 0 && newRecipe?.id) { await insertRecipeCategories(newRecipe.id, categories); } reset(); router.push(`/recipe_page?id=${newRecipe?.id}`); } catch (error) { console.error('Error inserting recipe or categories:', error); alert('Failed to insert recipe'); } }; return ( <AuthenticatedPage> <div className='max-w-3xl mx-auto mt-10 p-6 bg-white text-gray-700 rounded shadow'> <div className='flex justify-between items-center mb-6'> <Link href='/home_page' className='border border-violet-300 bg-white text-gray-800 hover:bg-violet-300 hover:text-gray-800 transition-colors rounded-xl flex items-center justify-center px-4 h-10' > Back </Link> <h2 className='text-2xl font-bold text-center flex-1'> Update Recipe </h2> </div> <form onSubmit={handleSubmit(onSubmit)} className='space-y-4'> <TextInput label='Recipe Name' placeholder='Enter recipe name' {...register('name', { required: true })} required variant='filled' className='w-full' /> {/* Difficulty Section */} <div className='mt-4'> <label className='block text-sm font-medium text-gray-700 mb-2'> Difficulty </label> <div className='flex space-x-4'> {[0, 1, 2].map((level) => ( <button key={level} type='button' className={`flex-1 py-2 rounded-md text-black ${difficulty === level ? 'bg-violet-300' : 'border bg-slate-200 hover:bg-slate-300'}`} onClick={() => handleDifficultyChange(level)} > {['Easy', 'Medium', 'Hard'][level]} </button> ))} </div> </div> <Controller control={control} name='prep_time' rules={{ required: true }} render={({ field: { value, onChange } }) => ( <NumberInput label='Prep Time (minutes)' placeholder='Prep time' value={value} onChange={onChange} required variant='filled' className='w-full' /> )} /> <Controller control={control} name='cook_time' render={({ field: { value, onChange } }) => ( <NumberInput label='Cook Time (minutes)' placeholder='Cook time' value={value} onChange={onChange} variant='filled' className='w-full' /> )} /> <Controller control={control} name='servings' render={({ field: { value, onChange } }) => ( <NumberInput label='Servings' placeholder='Servings' value={value} onChange={onChange} variant='filled' className='w-full' /> )} /> <Controller control={control} name='shared' render={({ field }) => ( <Switch label='Shared' checked={field.value} onChange={(event) => field.onChange(event.currentTarget.checked)} color={'#DBCDF0'} /> )} /> {/* MultiSelect for Categories */} <Controller control={control} name='categories' render={({ field }) => ( <MultiSelect label='Categories' placeholder={categoriesLoading ? 'Loading categories...' : 'Select categories'} data={categoryOptions} value={field.value.map(String)} onChange={(values) => field.onChange(values.map(Number))} searchable nothingFoundMessage='No categories found' className='w-full' disabled={categoriesLoading} /> )} /> {/* Label and File input for images */} <div className='flex flex-col'> <label className='mb-1 font-medium'>Recipe Images</label> <Controller control={control} name='images' render={({ field: { onChange, ref } }) => ( <input type='file' multiple accept='image/*' onChange={(e) => onChange(e.target.files)} ref={ref} title='Upload Images' className='block w-full text-sm text-gray-500 file:mr-4 file:py-2 file:px-4 file:rounded file:border-0 file:text-sm file:font-semibold file:bg-violet-200 file:text-gray-800 hover:file:bg-violet-100' /> )} /> </div> {/* Structured Ingredients */} <div className='border p-4 rounded'> <h3 className='font-bold mb-2'>Ingredients</h3> {ingredientFields.map((field, index) => ( <div key={field.id} className='flex gap-2 mb-2'> <TextInput placeholder='Name' {...register(`ingredients.${index}.name` as const, { required: true })} className='flex-1' /> <Controller control={control} name={`ingredients.${index}.amount` as const} rules={{ required: true }} render={({ field: { value, onChange } }) => ( <NumberInput placeholder='Amount' value={value} onChange={onChange} className='w-24' /> )} /> <TextInput placeholder='Unit' {...register(`ingredients.${index}.unit` as const, { required: true })} className='w-24' /> <Button color='red' onClick={() => removeIngredient(index)} > Remove </Button> </div> ))} <button type='button' className='bg-slate-200 text-black rounded-md hover:bg-slate-100 transition-all flex items-center justify-center px-4 h-10' onClick={() => appendIngredient({ name: '', amount: 0, unit: '' })} > Add Ingredient </button> </div> {/* Structured Directions */} <div className='border p-4 rounded'> <h3 className='font-bold mb-2'>Directions</h3> {directionFields.map((field, index) => ( <div key={field.id} className='flex gap-2 mb-2'> <Textarea placeholder={`Step ${index + 1}`} {...register(`directions.${index}.instruction` as const, { required: true })} className='flex-1' /> <Button color='red' onClick={() => removeDirection(index)} > Remove </Button> </div> ))} <button type='button' className='bg-slate-200 text-black rounded-md hover:bg-slate-100 transition-all flex items-center justify-center px-4 h-10' onClick={() => appendDirection({ instruction: '' })} > Add Direction </button> </div> {/* Structured Notes */} <div className='border p-4 rounded'> <h3 className='font-bold mb-2'>Notes</h3> {noteFields.map((field, index) => ( <div key={field.id} className='flex gap-2 mb-2'> <Textarea placeholder={`Note ${index + 1}`} {...register(`notes.${index}.note` as const, { required: true })} className='flex-1' /> <Button color='red' onClick={() => removeNote(index)} > Remove </Button> </div> ))} <button type='button' className='bg-slate-200 text-black rounded-md hover:bg-slate-100 transition-all flex items-center justify-center px-4 h-10' onClick={() => appendNote({ note: '' })} > Add Note </button> </div> <button type='submit' className={`rounded-xl transition-colors flex items-center justify-center text-sm h-10 w-full px-4 bg-violet-300 text-black ${isPending ? 'opacity-50 cursor-not-allowed' : 'hover:bg-white hover:border hover:border-violet-400'}`} disabled={isPending} // Disable button when loading > {isPending ? 'Loading...' : 'Insert Recipe'} </button> </form> </div> </AuthenticatedPage> ); } export default UpdateRecipeClient;Key Changes Made:
-
Fetching Existing Recipe: The useEffect hook fetches the recipe data based on the
recipeIdpassed via URL parameters. This allows pre-filling the form with the current recipe details when editing. -
Form Resetting: After fetching the recipe details, the form is reset with new initial values to populate the fields properly using
reset(completeData). -
Field Values Handling: Use
setValuefor handling the "difficulty" state to ensure that the difficulty level is appropriately set when the recipe is being edited. -
Error Handling: Added error handling for recipe fetching to improve robustness.
Notes:
- Ensure that
user_idis set correctly according to your authentication context. - The structure for ingredients, directions, and notes must match the format expected by your backend.
- Adjust the URL for
fetchand any other helper functions as necessary based on your specific implementation.
With these changes, your component should now automatically populate the fields based on the recipe details fetched using the
recipeId. Let me know if you need further adjustments or specific functionality! -
- User
handledifficultychange has an error and so does setvalue
- Assistant
Let's address the issues with
handleDifficultyChangeandsetValue. I’ll make sure your form handles the difficulty change correctly while usingreact-hook-form.Firstly, I'll update the
handleDifficultyChangeto ensure it works properly. Then, I'll ensure thatsetValueis being used correctly within the context of the component regarding the difficulty state.Corrected
UpdateRecipeClientComponentHere's an updated version of the
UpdateRecipeClientcomponent, focusing on fixinghandleDifficultyChangeand ensuringsetValueworks correctly:'use client'; import { useForm, useFieldArray, Controller } from 'react-hook-form'; import { TextInput, Textarea, NumberInput, Switch, Button, MultiSelect, Loader, } from '@mantine/core'; import Link from 'next/link'; import { useRouter, useSearchParams } from 'next/navigation'; import { useEffect, useState } from 'react'; // Import useEffect and useState import { useInsertRecipe } from '@/hooks/useInsertRecipe'; import { useFetchAll } from '@/hooks/useFetchAll'; import { uploadImages, insertRecipeCategories, fetch, fetchAll, } from '@/services/supabase_service'; import { Json } from '@/models/json'; import AuthenticatedPage from '@/components/authenticated_page/authenticated_page'; interface Ingredient { name: string; amount: number; unit: string; } interface DirectionStep { instruction: string; } interface Note { note: string; } interface RecipeFormValues { user_id: string; name: string; difficulty: number; prep_time: number; cook_time?: number; servings?: number; shared?: boolean; ingredients: Ingredient[]; directions: DirectionStep[]; notes?: Note[] | null; images: FileList | null; videos: null; categories: number[]; // Selected category IDs (for join table) } function UpdateRecipeClient() { const searchParams = useSearchParams(); const recipeId = searchParams.get('id') || ''; const router = useRouter(); const { register, handleSubmit, control, reset, setValue } = useForm<RecipeFormValues>({ defaultValues: { user_id: '', // Set this dynamically from your user auth context/store. name: '', difficulty: 0, prep_time: 0, cook_time: 0, servings: 0, shared: false, ingredients: [{ name: '', amount: 0, unit: '' }], directions: [{ instruction: '' }], notes: null, images: null, videos: null, categories: [], }, mode: 'onChange', }); // Field arrays for structured fields const { fields: ingredientFields, append: appendIngredient, remove: removeIngredient, } = useFieldArray({ control, name: 'ingredients', }); const { fields: directionFields, append: appendDirection, remove: removeDirection, } = useFieldArray({ control, name: 'directions', }); const { fields: noteFields, append: appendNote, remove: removeNote, } = useFieldArray({ control, name: 'notes', }); // Fetch categories using useFetchAll (table: 'categories') with pagination disabled. const { data: categoriesData, isLoading: categoriesLoading } = useFetchAll({ table: 'categories', usePagination: false, }); const categoryOptions = (categoriesData?.data as { id: number; name: string }[] | undefined)?.map( (cat) => ({ value: cat.id.toString(), label: cat.name, }), ) || []; const { mutateAsync, isPending } = useInsertRecipe(); const [difficulty, setDifficulty] = useState<number>(0); // Handle Difficulty Change const handleDifficultyChange = (value: number) => { setDifficulty(value); setValue('difficulty', value); // Set the difficulty in the form state }; // Fetch the recipe details to pre-fill the form useEffect(() => { if (recipeId) { fetch<RecipeFormValues>('recipes', recipeId) .then(async (recipeData) => { // Fetch associated categories const catResult = await fetchAll({ table: 'recipe_categories', filters: [{ column: 'recipe_id', value: recipeId, operator: 'eq' }], usePagination: false, }); const recipeCategories = catResult.data.map((row) => row.category_id); const completeData = { ...recipeData, categories: recipeCategories || [], }; // Use reset to fill in the form reset(completeData); // Also set the difficulty setDifficulty(recipeData.difficulty || 0); // Set difficulty from fetched recipe data setValue('difficulty', recipeData.difficulty || 0); // Ensure it reflects in the form state }) .catch((error) => { console.error('Error fetching recipe:', error); alert('Failed to load recipe for editing'); }); } }, [recipeId, reset, setValue]); const onSubmit = async (values: RecipeFormValues) => { // Process image uploads if files are selected. let imageUrls: string[] | null = null; if (values.images && values.images.length > 0) { const filesArray = Array.from(values.images); try { imageUrls = await uploadImages(filesArray); } catch (error) { alert('Image upload failed'); console.error(error); return; } } const { categories, ...recipeData } = values; // Auto-calculate total_time as prep_time + cook_time (default cook_time to 0 if undefined) const computedTotalTime = values.prep_time + (values.cook_time ?? 0); const recipePayload = { ...recipeData, total_time: computedTotalTime, ingredients: values.ingredients as unknown as Json, directions: values.directions as unknown as Json, notes: values.notes as unknown as Json, images: imageUrls, }; try { const recipeDataResponse = await mutateAsync(recipePayload); const newRecipe = Array.isArray(recipeDataResponse) ? recipeDataResponse[0] : recipeDataResponse; if (categories.length > 0 && newRecipe?.id) { await insertRecipeCategories(newRecipe.id, categories); } reset(); router.push(`/recipe_page?id=${newRecipe?.id}`); } catch (error) { console.error('Error inserting recipe or categories:', error); alert('Failed to insert recipe'); } }; return ( <AuthenticatedPage> <div className='max-w-3xl mx-auto mt-10 p-6 bg-white text-gray-700 rounded shadow'> <div className='flex justify-between items-center mb-6'> <Link href='/home_page' className='border border-violet-300 bg-white text-gray-800 hover:bg-violet-300 hover:text-gray-800 transition-colors rounded-xl flex items-center justify-center px-4 h-10' > Back </Link> <h2 className='text-2xl font-bold text-center flex-1'> Update Recipe </h2> </div> <form onSubmit={handleSubmit(onSubmit)} className='space-y-4'> <TextInput label='Recipe Name' placeholder='Enter recipe name' {...register('name', { required: true })} required variant='filled' className='w-full' /> {/* Difficulty Section */} <div className='mt-4'> <label className='block text-sm font-medium text-gray-700 mb-2'> Difficulty </label> <div className='flex space-x-4'> {[0, 1, 2].map((level) => ( <button key={level} type='button' className={`flex-1 py-2 rounded-md text-black ${difficulty === level ? 'bg-violet-300' : 'border bg-slate-200 hover:bg-slate-300'}`} onClick={() => handleDifficultyChange(level)} > {['Easy', 'Medium', 'Hard'][level]} </button> ))} </div> </div> <Controller control={control} name='prep_time' rules={{ required: true }} render={({ field: { value, onChange } }) => ( <NumberInput label='Prep Time (minutes)' placeholder='Prep time' value={value} onChange={onChange} required variant='filled' className='w-full' /> )} /> <Controller control={control} name='cook_time' render={({ field: { value, onChange } }) => ( <NumberInput label='Cook Time (minutes)' placeholder='Cook time' value={value} onChange={onChange} variant='filled' className='w-full' /> )} /> <Controller control={control} name='servings' render={({ field: { value, onChange } }) => ( <NumberInput label='Servings' placeholder='Servings' value={value} onChange={onChange} variant='filled' className='w-full' /> )} /> <Controller control={control} name='shared' render={({ field }) => ( <Switch label='Shared' checked={field.value} onChange={(event) => field.onChange(event.currentTarget.checked)} color={'#DBCDF0'} /> )} /> {/* MultiSelect for Categories */} <Controller control={control} name='categories' render={({ field }) => ( <MultiSelect label='Categories' placeholder={categoriesLoading ? 'Loading categories...' : 'Select categories'} data={categoryOptions} value={field.value.map(String)} onChange={(values) => field.onChange(values.map(Number))} searchable nothingFoundMessage='No categories found' className='w-full' disabled={categoriesLoading} /> )} /> {/* Label and File input for images */} <div className='flex flex-col'> <label className='mb-1 font-medium'>Recipe Images</label> <Controller control={control} name='images' render={({ field: { onChange, ref } }) => ( <input type='file' multiple accept='image/*' onChange={(e) => onChange(e.target.files)} ref={ref} title='Upload Images' className='block w-full text-sm text-gray-500 file:mr-4 file:py-2 file:px-4 file:rounded file:border-0 file:text-sm file:font-semibold file:bg-violet-200 file:text-gray-800 hover:file:bg-violet-100' /> )} /> </div> {/* Structured Ingredients */} <div className='border p-4 rounded'> <h3 className='font-bold mb-2'>Ingredients</h3> {ingredientFields.map((field, index) => ( <div key={field.id} className='flex gap-2 mb-2'> <TextInput placeholder='Name' {...register(`ingredients.${index}.name` as const, { required: true })} className='flex-1' /> <Controller control={control} name={`ingredients.${index}.amount` as const} rules={{ required: true }} render={({ field: { value, onChange } }) => ( <NumberInput placeholder='Amount' value={value} onChange={onChange} className='w-24' /> )} /> <TextInput placeholder='Unit' {...register(`ingredients.${index}.unit` as const, { required: true })} className='w-24' /> <Button color='red' onClick={() => removeIngredient(index)} > Remove </Button> </div> ))} <button type='button' className='bg-slate-200 text-black rounded-md hover:bg-slate-100 transition-all flex items-center justify-center px-4 h-10' onClick={() => appendIngredient({ name: '', amount: 0, unit: '' })} > Add Ingredient </button> </div> {/* Structured Directions */} <div className='border p-4 rounded'> <h3 className='font-bold mb-2'>Directions</h3> {directionFields.map((field, index) => ( <div key={field.id} className='flex gap-2 mb-2'> <Textarea placeholder={`Step ${index + 1}`} {...register(`directions.${index}.instruction` as const, { required: true })} className='flex-1' /> <Button color='red' onClick={() => removeDirection(index)} > Remove </Button> </div> ))} <button type='button' className='bg-slate-200 text-black rounded-md hover:bg-slate-100 transition-all flex items-center justify-center px-4 h-10' onClick={() => appendDirection({ instruction: '' })} > Add Direction </button> </div> {/* Structured Notes */} <div className='border p-4 rounded'> <h3 className='font-bold mb-2'>Notes</h3> {noteFields.map((field, index) => ( <div key={field.id} className='flex gap-2 mb-2'> <Textarea placeholder={`Note ${index + 1}`} {...register(`notes.${index}.note` as const, { required: true })} className='flex-1' /> <Button color='red' onClick={() => removeNote(index)} > Remove </Button> </div> ))} <button type='button' className='bg-slate-200 text-black rounded-md hover:bg-slate-100 transition-all flex items-center justify-center px-4 h-10' onClick={() => appendNote({ note: '' })} > Add Note </button> </div> <button type='submit' className={`rounded-xl transition-colors flex items-center justify-center text-sm h-10 w-full px-4 bg-violet-300 text-black ${isPending ? 'opacity-50 cursor-not-allowed' : 'hover:bg-white hover:border hover:border-violet-400'}`} disabled={isPending} // Disable button when loading > {isPending ? 'Loading...' : 'Insert Recipe'} </button> </form> </div> </AuthenticatedPage> ); } export default UpdateRecipeClient;Summary of Changes:
-
Set Difficulty on Fetch: When the recipe data is fetched in the
useEffect, it sets both the local statedifficultyand the form value usingsetValue('difficulty', recipeData.difficulty || 0);. -
Corrected
handleDifficultyChange: This function now correctly sets the difficulty both in the local state and updates the form value usingsetValue. -
Removed Extra Imports: Made sure
useEffectanduseStateare imported correctly.
By making these adjustments, the handling of difficulty changes and setting of values within the form should work without errors. Make sure the rest of your environment and hooks are functioning as expected. If you encounter any other specific issues, feel free to share those as well!
-
- User
it works fine but none of the fields are filled, meanin the recipe name label should have taken the value of the name from the recipe records of that recipe id and etc
- Assistant
To ensure that the form fields are populated with the values from the fetched recipe data, we need to make sure that the
reset()function is called with the correct data structure, and we should carefully check the fetched data from thefetchcall.In the
UpdateRecipeClientcomponent, after you fetch the recipe data, you should confirm that each property you're trying to fill in the form correctly corresponds to the keys in the fetchedrecipeData.Let's make sure we adjust the
reset()function appropriately and ensure that the fetched fields are being correctly set into the form state.Ensure Proper Mapping for Form Fields
Updated
UpdateRecipeClientwith Proper Reset CallHere's a detailed breakdown with enhancements to ensure the fields are filled correctly:
'use client'; import { useForm, useFieldArray, Controller } from 'react-hook-form'; import { TextInput, Textarea, NumberInput, Switch, Button, MultiSelect, Loader, } from '@mantine/core'; import Link from 'next/link'; import { useRouter, useSearchParams } from 'next/navigation'; import { useEffect, useState } from 'react'; // Import useEffect and useState import { useInsertRecipe } from '@/hooks/useInsertRecipe'; import { useFetchAll } from '@/hooks/useFetchAll'; import { uploadImages, insertRecipeCategories, fetch, fetchAll, } from '@/services/supabase_service'; import { Json } from '@/models/json'; import AuthenticatedPage from '@/components/authenticated_page/authenticated_page'; interface Ingredient { name: string; amount: number; unit: string; } interface DirectionStep { instruction: string; } interface Note { note: string; } interface RecipeFormValues { user_id: string; name: string; difficulty: number; prep_time: number; cook_time?: number; servings?: number; shared?: boolean; ingredients: Ingredient[]; directions: DirectionStep[]; notes?: Note[] | null; images: FileList | null; videos: null; categories: number[]; // Selected category IDs (for join table) } function UpdateRecipeClient() { const searchParams = useSearchParams(); const recipeId = searchParams.get('id') || ''; const router = useRouter(); const { register, handleSubmit, control, reset, setValue } = useForm<RecipeFormValues>({ defaultValues: { user_id: '', // Set this dynamically from your user auth context/store. name: '', difficulty: 0, prep_time: 0, cook_time: 0, servings: 0, shared: false, ingredients: [{ name: '', amount: 0, unit: '' }], directions: [{ instruction: '' }], notes: null, images: null, videos: null, categories: [], }, mode: 'onChange', }); // Field arrays for structured fields const { fields: ingredientFields, append: appendIngredient, remove: removeIngredient, } = useFieldArray({ control, name: 'ingredients', }); const { fields: directionFields, append: appendDirection, remove: removeDirection, } = useFieldArray({ control, name: 'directions', }); const { fields: noteFields, append: appendNote, remove: removeNote, } = useFieldArray({ control, name: 'notes', }); // Fetch categories using useFetchAll (table: 'categories') with pagination disabled. const { data: categoriesData, isLoading: categoriesLoading } = useFetchAll({ table: 'categories', usePagination: false, }); const categoryOptions = (categoriesData?.data as { id: number; name: string }[] | undefined)?.map( (cat) => ({ value: cat.id.toString(), label: cat.name, }), ) || []; const { mutateAsync, isPending } = useInsertRecipe(); const [difficulty, setDifficulty] = useState<number>(0); // Handle Difficulty Change const handleDifficultyChange = (value: number) => { setDifficulty(value); setValue('difficulty', value); // Set the difficulty in the form state }; // Fetch the recipe details to pre-fill the form useEffect(() => { if (recipeId) { fetch<RecipeFormValues>('recipes', recipeId) .then(async (recipeData) => { // Fetch associated categories const catResult = await fetchAll({ table: 'recipe_categories', filters: [{ column: 'recipe_id', value: recipeId, operator: 'eq' }], usePagination: false, }); const recipeCategories = catResult.data.map((row) => row.category_id); // Prepare artichoke data from the fetched recipe const completeData: RecipeFormValues = { user_id: recipeData.user_id, name: recipeData.name, difficulty: recipeData.difficulty, prep_time: recipeData.prep_time, cook_time: recipeData.cook_time || 0, servings: recipeData.servings || 0, shared: recipeData.shared || false, ingredients: recipeData.ingredients || [], directions: recipeData.directions || [], notes: recipeData.notes || null, images: null, // Keep the images null because you probably have a separate upload mechanism videos: null, categories: recipeCategories, }; // Use reset to fill in the form reset(completeData); // Also set the difficulty setDifficulty(completeData.difficulty); // Set difficulty from fetched recipe data setValue('difficulty', completeData.difficulty); // Ensure it reflects in the form state }) .catch((error) => { console.error('Error fetching recipe:', error); alert('Failed to load recipe for editing'); }); } }, [recipeId, reset, setValue]); const onSubmit = async (values: RecipeFormValues) => { // Process image uploads if files are selected. let imageUrls: string[] | null = null; if (values.images && values.images.length > 0) { const filesArray = Array.from(values.images); try { imageUrls = await uploadImages(filesArray); } catch (error) { alert('Image upload failed'); console.error(error); return; } } const { categories, ...recipeData } = values; // Auto-calculate total_time as prep_time + cook_time (default cook_time to 0 if undefined) const computedTotalTime = values.prep_time + (values.cook_time ?? 0); const recipePayload = { ...recipeData, total_time: computedTotalTime, ingredients: values.ingredients as unknown as Json, directions: values.directions as unknown as Json, notes: values.notes as unknown as Json, images: imageUrls, }; try { const recipeDataResponse = await mutateAsync(recipePayload); const newRecipe = Array.isArray(recipeDataResponse) ? recipeDataResponse[0] : recipeDataResponse; if (categories.length > 0 && newRecipe?.id) { await insertRecipeCategories(newRecipe.id, categories); } reset(); router.push(`/recipe_page?id=${newRecipe?.id}`); } catch (error) { console.error('Error inserting recipe or categories:', error); alert('Failed to insert recipe'); } }; return ( <AuthenticatedPage> <div className='max-w-3xl mx-auto mt-10 p-6 bg-white text-gray-700 rounded shadow'> <div className='flex justify-between items-center mb-6'> <Link href='/home_page' className='border border-violet-300 bg-white text-gray-800 hover:bg-violet-300 hover:text-gray-800 transition-colors rounded-xl flex items-center justify-center px-4 h-10' > Back </Link> <h2 className='text-2xl font-bold text-center flex-1'> Update Recipe </h2> </div> <form onSubmit={handleSubmit(onSubmit)} className='space-y-4'> <TextInput label='Recipe Name' placeholder='Enter recipe name' {...register('name', { required: true })} required variant='filled' className='w-full' /> {/* Difficulty Section */} <div className='mt-4'> <label className='block text-sm font-medium text-gray-700 mb-2'> Difficulty </label> <div className='flex space-x-4'> {[0, 1, 2].map((level) => ( <button key={level} type='button' className={`flex-1 py-2 rounded-md text-black ${difficulty === level ? 'bg-violet-300' : 'border bg-slate-200 hover:bg-slate-300'}`} onClick={() => handleDifficultyChange(level)} > {['Easy', 'Medium', 'Hard'][level]} </button> ))} </div> </div> <Controller control={control} name='prep_time' rules={{ required: true }} render={({ field: { value, onChange } }) => ( <NumberInput label='Prep Time (minutes)' placeholder='Prep time' value={value} onChange={onChange} required variant='filled' className='w-full' /> )} /> <Controller control={control} name='cook_time' render={({ field: { value, onChange } }) => ( <NumberInput label='Cook Time (minutes)' placeholder='Cook time' value={value} onChange={onChange} variant='filled' className='w-full' /> )} /> <Controller control={control} name='servings' render={({ field: { value, onChange } }) => ( <NumberInput label='Servings' placeholder='Servings' value={value} onChange={onChange} variant='filled' className='w-full' /> )} /> <Controller control={control} name='shared' render={({ field }) => ( <Switch label='Shared' checked={field.value} onChange={(event) => field.onChange(event.currentTarget.checked)} color={'#DBCDF0'} /> )} /> {/* MultiSelect for Categories */} <Controller control={control} name='categories' render={({ field }) => ( <MultiSelect label='Categories' placeholder={categoriesLoading ? 'Loading categories...' : 'Select categories'} data={categoryOptions} value={field.value.map(String)} onChange={(values) => field.onChange(values.map(Number))} searchable nothingFoundMessage='No categories found' className='w-full' disabled={categoriesLoading} /> )} /> {/* Label and File input for images */} <div className='flex flex-col'> <label className='mb-1 font-medium'>Recipe Images</label> <Controller control={control} name='images' render={({ field: { onChange, ref } }) => ( <input type='file' multiple accept='image/*' onChange={(e) => onChange(e.target.files)} ref={ref} title='Upload Images' className='block w-full text-sm text-gray-500 file:mr-4 file:py-2 file:px-4 file:rounded file:border-0 file:text-sm file:font-semibold file:bg-violet-200 file:text-gray-800 hover:file:bg-violet-100' /> )} /> </div> {/* Structured Ingredients */} <div className='border p-4 rounded'> <h3 className='font-bold mb-2'>Ingredients</h3> {ingredientFields.map((field, index) => ( <div key={field.id} className='flex gap-2 mb-2'> <TextInput placeholder='Name' {...register(`ingredients.${index}.name` as const, { required: true })} className='flex-1' /> <Controller control={control} name={`ingredients.${index}.amount` as const} rules={{ required: true }} render={({ field: { value, onChange } }) => ( <NumberInput placeholder='Amount' value={value} onChange={onChange} className='w-24' /> )} /> <TextInput placeholder='Unit' {...register(`ingredients.${index}.unit` as const, { required: true })} className='w-24' /> <Button color='red' onClick={() => removeIngredient(index)} > Remove </Button> </div> ))} <button type='button' className='bg-slate-200 text-black rounded-md hover:bg-slate-100 transition-all flex items-center justify-center px-4 h-10' onClick={() => appendIngredient({ name: '', amount: 0, unit: '' })} > Add Ingredient </button> </div> {/* Structured Directions */} <div className='border p-4 rounded'> <h3 className='font-bold mb-2'>Directions</h3> {directionFields.map((field, index) => ( <div key={field.id} className='flex gap-2 mb-2'> <Textarea placeholder={`Step ${index + 1}`} {...register(`directions.${index}.instruction` as const, { required: true })} className='flex-1' /> <Button color='red' onClick={() => removeDirection(index)} > Remove </Button> </div> ))} <button type='button' className='bg-slate-200 text-black rounded-md hover:bg-slate-100 transition-all flex items-center justify-center px-4 h-10' onClick={() => appendDirection({ instruction: '' })} > Add Direction </button> </div> {/* Structured Notes */} <div className='border p-4 rounded'> <h3 className='font-bold mb-2'>Notes</h3> {noteFields.map((field, index) => ( <div key={field.id} className='flex gap-2 mb-2'> <Textarea placeholder={`Note ${index + 1}`} {...register(`notes.${index}.note` as const, { required: true })} className='flex-1' /> <Button color='red' onClick={() => removeNote(index)} > Remove </Button> </div> ))} <button type='button' className='bg-slate-200 text-black rounded-md hover:bg-slate-100 transition-all flex items-center justify-center px-4 h-10' onClick={() => appendNote({ note: '' })} > Add Note </button> </div> <button type='submit' className={`rounded-xl transition-colors flex items-center justify-center text-sm h-10 w-full px-4 bg-violet-300 text-black ${isPending ? 'opacity-50 cursor-not-allowed' : 'hover:bg-white hover:border hover:border-violet-400'}`} disabled={isPending} // Disable button when loading > {isPending ? 'Loading...' : 'Insert Recipe'} </button> </form> </div> </AuthenticatedPage> ); } export default UpdateRecipeClient;Key Adjustments:
-
Complete Data Object: When resetting the form with
reset(completeData), I ensured that the data structure has values coming fromrecipeDatacorrectly populated. -
Ingredients and Directions: For
ingredientsanddirections, make sure that the fetched values are in the correct format. If the data coming back from the API for these fields needs to be parsed (e.g., from JSON), ensure you handle that before resetting the state. -
Check the Fetched Data Structure:
- Make sure the keys in
recipeDatamatch exactly how your backend sends that data. If they do not, you will need to map the values properly. - Confirm that the
ingredients,directions, andnotesin the fetched data are arrays (as per your form's expectations).
- Make sure the keys in
By following these steps, your form should now populate correctly with the recipe details fetched from the database. If it's still not working, try logging the output of
recipeDataafter fetching to see how it is structured and adjust the code accordingly. -
- User
'use client';
import { useForm, useFieldArray, Controller } from 'react-hook-form'; import { TextInput, Textarea, NumberInput, Switch, Button, MultiSelect, } from '@mantine/core'; import Link from 'next/link'; import { useRouter, useSearchParams } from 'next/navigation'; import { useEffect, useState } from 'react'; // Import useEffect and useState import { useInsertRecipe } from '@/hooks/useInsertRecipe'; import { useFetchAll } from '@/hooks/useFetchAll'; import { uploadImages, insertRecipeCategories, fetch, fetchAll, RecipeRecord, } from '@/services/supabase_service'; import { Json } from '@/models/json'; import AuthenticatedPage from '@/components/authenticated_page/authenticated_page';
interface Ingredient { name: string; amount: number; unit: string; }
interface DirectionStep { instruction: string; }
interface Note { note: string; }
interface RecipeFormValues { user_id: string; name: string; difficulty: number; prep_time: number; cook_time?: number; servings?: number; shared?: boolean; ingredients: Ingredient[]; directions: DirectionStep[]; notes?: Note[] | null; images: FileList | null; videos: null; categories: number[]; // Selected category IDs (for join table) }
function UpdateRecipeClient() { const searchParams = useSearchParams(); const [recipe, setRecipe] = useState<RecipeRecord | null>(null); const recipeId = searchParams.get('id') || ''; const router = useRouter();
const { register, handleSubmit, control, reset, setValue } = useForm({ defaultValues: { user_id: '', // Set this dynamically from your user auth context/store. name: '', difficulty: 0, prep_time: 0, cook_time: 0, servings: 0, shared: false, ingredients: [{ name: '', amount: 0, unit: '' }], directions: [{ instruction: '' }], notes: null, images: null, videos: null, categories: [], }, mode: 'onChange', });
// Field arrays for structured fields const { fields: ingredientFields, append: appendIngredient, remove: removeIngredient, } = useFieldArray({ control, name: 'ingredients', });
const { fields: directionFields, append: appendDirection, remove: removeDirection, } = useFieldArray({ control, name: 'directions', });
const { fields: noteFields, append: appendNote, remove: removeNote, } = useFieldArray({ control, name: 'notes', });
// Fetch categories using useFetchAll (table: 'categories') with pagination disabled. const { data: categoriesData, isLoading: categoriesLoading } = useFetchAll({ table: 'categories', usePagination: false, });
const categoryOptions = (categoriesData?.data as { id: number; name: string }[] | undefined)?.map( (cat) => ({ value: cat.id.toString(), label: cat.name, }), ) || [];
const { mutateAsync, isPending } = useInsertRecipe(); const [difficulty, setDifficulty] = useState(0);
// Handle Difficulty Change const handleDifficultyChange = (value: number) => { setDifficulty(value); setValue('difficulty', value); // Set the difficulty in the form state };
// Fetch the recipe details to pre-fill the form useEffect(() => { if (recipeId) { fetch('recipes', recipeId) .then(async (recipeData) => { // Fetch associated categories const catResult = await fetchAll({ table: 'recipe_categories', filters: [{ column: 'recipe_id', value: recipeId, operator: 'eq' }], usePagination: false, }); const recipeCategories = catResult.data.map((row) => row.category_id);
// Prepare artichoke data from the fetched recipe const completeData: RecipeFormValues = { user_id: recipeData.user_id, name: recipeData.name, difficulty: recipeData.difficulty, prep_time: recipeData.prep_time, cook_time: recipeData.cook_time || 0, servings: recipeData.servings || 0, shared: recipeData.shared || false, ingredients: recipeData.ingredients || [], directions: recipeData.directions || [], notes: recipeData.notes || null, images: null, // Keep the images null because you probably have a separate upload mechanism videos: null, categories: recipeCategories, }; // Use reset to fill in the form reset(completeData); // Also set the difficulty setDifficulty(completeData.difficulty); // Set difficulty from fetched recipe data setValue('difficulty', completeData.difficulty); // Ensure it reflects in the form state }) .catch((error) => { console.error('Error fetching recipe:', error); alert('Failed to load recipe for editing'); }); }}, [recipeId, reset, setValue]);
const onSubmit = async (values: RecipeFormValues) => { // Process image uploads if files are selected. let imageUrls: string[] | null = null; if (values.images && values.images.length > 0) { const filesArray = Array.from(values.images); try { imageUrls = await uploadImages(filesArray); } catch (error) { alert('Image upload failed'); console.error(error); return; } }
const { categories, ...recipeData } = values; // Auto-calculate total_time as prep_time + cook_time (default cook_time to 0 if undefined) const computedTotalTime = values.prep_time + (values.cook_time ?? 0); const recipePayload = { ...recipeData, total_time: computedTotalTime, ingredients: values.ingredients as unknown as Json, directions: values.directions as unknown as Json, notes: values.notes as unknown as Json, images: imageUrls, }; try { const recipeDataResponse = await mutateAsync(recipePayload); const newRecipe = Array.isArray(recipeDataResponse) ? recipeDataResponse[0] : recipeDataResponse; if (categories.length > 0 && newRecipe?.id) { await insertRecipeCategories(newRecipe.id, categories); } reset(); router.push(`/recipe_page?id=${newRecipe?.id}`); } catch (error) { console.error('Error inserting recipe or categories:', error); alert('Failed to insert recipe'); }};
return ( Back Update Recipe <TextInput label='Recipe Name' placeholder='Enter recipe name' {...register('name', { required: true })} required variant='filled' className='w-full' /> {/* Difficulty Section /} Difficulty {[0, 1, 2].map((level) => ( <button key={level} type='button' className={
flex-1 py-2 rounded-md text-black ${ difficulty === level ? 'bg-violet-300' : 'border bg-slate-200 hover:bg-slate-300' }} onClick={() => handleDifficultyChange(level)} > {['Easy', 'Medium', 'Hard'][level]} ))} <Controller control={control} name='prep_time' rules={{ required: true }} render={({ field: { value, onChange } }) => ( )} /> <Controller control={control} name='cook_time' render={({ field: { value, onChange } }) => ( )} /> <Controller control={control} name='servings' render={({ field: { value, onChange } }) => ( )} /> <Controller control={control} name='shared' render={({ field }) => ( <Switch label='Shared' checked={field.value} onChange={(event) => field.onChange(event.currentTarget.checked) } color={'#DBCDF0'} /> )} /> {/ MultiSelect for Categories /} <Controller control={control} name='categories' render={({ field }) => ( <MultiSelect label='Categories' placeholder={ categoriesLoading ? 'Loading categories...' : 'Select categories' } data={categoryOptions} value={field.value.map(String)} onChange={(values) => field.onChange(values.map(Number))} searchable nothingFoundMessage='No categories found' className='w-full' disabled={categoriesLoading} /> )} /> {/ Label and File input for images /} Recipe Images <Controller control={control} name='images' render={({ field: { onChange, ref } }) => ( <input type='file' multiple accept='image/' onChange={(e) => onChange(e.target.files)} ref={ref} title='Upload Images' className='block w-full text-sm text-gray-500 file:mr-4 file:py-2 file:px-4 file:rounded file:border-0 file:text-sm file:font-semibold file:bg-violet-200 file:text-gray-800 hover:file:bg-violet-100' /> )} /> {/* Structured Ingredients /} Ingredients {ingredientFields.map((field, index) => ( <TextInput placeholder='Name' {...register(ingredients.${index}.nameas const, { required: true, })} className='flex-1' /> <Controller control={control} name={ingredients.${index}.amountas const} rules={{ required: true }} render={({ field: { value, onChange } }) => ( )} /> <TextInput placeholder='Unit' {...register(ingredients.${index}.unitas const, { required: true, })} className='w-24' /> <Button color='red' onClick={() => removeIngredient(index)} > Remove ))} <button type='button' className='bg-slate-200 text-black rounded-md hover:bg-slate-100 transition-all flex items-center justify-center px-4 h-10' onClick={() => appendIngredient({ name: '', amount: 0, unit: '' }) } > Add Ingredient {/ Structured Directions /} Directions {directionFields.map((field, index) => ( <Textarea placeholder={Step ${index + 1}} {...register(directions.${index}.instructionas const, { required: true, })} className='flex-1' /> <Button color='red' onClick={() => removeDirection(index)} > Remove ))} <button type='button' className='bg-slate-200 text-black rounded-md hover:bg-slate-100 transition-all flex items-center justify-center px-4 h-10' onClick={() => appendDirection({ instruction: '' })} > Add Direction {/ Structured Notes */} Notes {noteFields.map((field, index) => ( <Textarea placeholder={Note ${index + 1}} {...register(notes.${index}.noteas const, { required: true, })} className='flex-1' /> <Button color='red' onClick={() => removeNote(index)} > Remove ))} <button type='button' className='bg-slate-200 text-black rounded-md hover:bg-slate-100 transition-all flex items-center justify-center px-4 h-10' onClick={() => appendNote({ note: '' })} > Add Note <button type='submit' className={rounded-xl transition-colors flex items-center justify-center text-sm h-10 w-full px-4 bg-violet-300 text-black ${ isPending ? 'opacity-50 cursor-not-allowed' : 'hover:bg-white hover:border hover:border-violet-400' }} disabled={isPending} // Disable button when loading > {isPending ? 'Loading...' : 'Insert Recipe'} ); }export default UpdateRecipeClient; the fields are all still blank and i dont wnat that ,
- Assistant
Thank you for your patience. Let's ensure that the fetched recipe details are correctly filled in all the fields of the form. The issue often comes down to how the data is structured or accessed within the
recipeDataobject.We'll take a step-by-step approach to ensure the recipe details correctly populate the form fields. Here are the things we need to focus on:
- Check Fetch Data Structure: Ensure that the fetched
recipeDatahas the correct structure that the form expects. - Ensure Proper Use of
reset(): Make sure we callreset()with the correctly structured object. - Logging the Fetched Data: Log the recipe data to see the structure we are actually getting and adjust accordingly.
Adjusted Code Based on Above Points
Here is the adjusted
UpdateRecipeClientcomponent, including checks and logs to help diagnose issues:'use client'; import { useForm, useFieldArray, Controller } from 'react-hook-form'; import { TextInput, Textarea, NumberInput, Switch, Button, MultiSelect, } from '@mantine/core'; import Link from 'next/link'; import { useRouter, useSearchParams } from 'next/navigation'; import { useEffect, useState } from 'react'; // Import useEffect and useState import { useInsertRecipe } from '@/hooks/useInsertRecipe'; import { useFetchAll } from '@/hooks/useFetchAll'; import { uploadImages, insertRecipeCategories, fetch, fetchAll, RecipeRecord, } from '@/services/supabase_service'; import { Json } from '@/models/json'; import AuthenticatedPage from '@/components/authenticated_page/authenticated_page'; interface Ingredient { name: string; amount: number; unit: string; } interface DirectionStep { instruction: string; } interface Note { note: string; } interface RecipeFormValues { user_id: string; name: string; difficulty: number; prep_time: number; cook_time?: number; servings?: number; shared?: boolean; ingredients: Ingredient[]; directions: DirectionStep[]; notes?: Note[] | null; images: FileList | null; videos: null; categories: number[]; // Selected category IDs (for join table) } function UpdateRecipeClient() { const searchParams = useSearchParams(); const recipeId = searchParams.get('id') || ''; const router = useRouter(); const { register, handleSubmit, control, reset, setValue } = useForm<RecipeFormValues>({ defaultValues: { user_id: '', // Set this dynamically from your user auth context/store. name: '', difficulty: 0, prep_time: 0, cook_time: 0, servings: 0, shared: false, ingredients: [{ name: '', amount: 0, unit: '' }], directions: [{ instruction: '' }], notes: null, images: null, videos: null, categories: [], }, mode: 'onChange', }); // Field arrays for structured fields const { fields: ingredientFields, append: appendIngredient, remove: removeIngredient, } = useFieldArray({ control, name: 'ingredients', }); const { fields: directionFields, append: appendDirection, remove: removeDirection, } = useFieldArray({ control, name: 'directions', }); const { fields: noteFields, append: appendNote, remove: removeNote, } = useFieldArray({ control, name: 'notes', }); // Fetch categories using useFetchAll (table: 'categories') with pagination disabled. const { data: categoriesData, isLoading: categoriesLoading } = useFetchAll({ table: 'categories', usePagination: false, }); const categoryOptions = (categoriesData?.data as { id: number; name: string }[] | undefined)?.map( (cat) => ({ value: cat.id.toString(), label: cat.name, }), ) || []; const { mutateAsync, isPending } = useInsertRecipe(); const [difficulty, setDifficulty] = useState<number>(0); // Handle Difficulty Change const handleDifficultyChange = (value: number) => { setDifficulty(value); setValue('difficulty', value); // Set the difficulty in the form state }; // Fetch the recipe details to pre-fill the form useEffect(() => { if (recipeId) { fetch<RecipeFormValues>('recipes', recipeId) .then(async (recipeData) => { console.log('Fetched recipe data:', recipeData); // Check what you are fetching // Fetch associated categories const catResult = await fetchAll({ table: 'recipe_categories', filters: [{ column: 'recipe_id', value: recipeId, operator: 'eq' }], usePagination: false, }); const recipeCategories = catResult.data.map((row) => row.category_id); // Check if ingredients data is in correct structure const ingredients = typeof recipeData.ingredients === 'string' ? JSON.parse(recipeData.ingredients) : recipeData.ingredients || []; const directions = typeof recipeData.directions === 'string' ? JSON.parse(recipeData.directions) : recipeData.directions || []; // Prepare complete data from the fetched recipe const completeData: RecipeFormValues = { user_id: recipeData.user_id, name: recipeData.name, difficulty: recipeData.difficulty, prep_time: recipeData.prep_time, cook_time: recipeData.cook_time || 0, servings: recipeData.servings || 0, shared: recipeData.shared || false, ingredients: ingredients, // Ensure to populate this correctly directions: directions, // Ensure to populate this correctly notes: recipeData.notes || null, images: null, // Keep the images null because you probably have a separate upload mechanism videos: null, categories: recipeCategories, }; // Use reset to fill in the form reset(completeData); console.log('Reset form with:', completeData); // Verify the reset data // Also set the difficulty setDifficulty(completeData.difficulty); // Set difficulty from fetched recipe data setValue('difficulty', completeData.difficulty); // Ensure it reflects in the form state }) .catch((error) => { console.error('Error fetching recipe:', error); alert('Failed to load recipe for editing'); }); } }, [recipeId, reset, setValue]); const onSubmit = async (values: RecipeFormValues) => { // Process image uploads if files are selected. let imageUrls: string[] | null = null; if (values.images && values.images.length > 0) { const filesArray = Array.from(values.images); try { imageUrls = await uploadImages(filesArray); } catch (error) { alert('Image upload failed'); console.error(error); return; } } const { categories, ...recipeData } = values; // Auto-calculate total_time as prep_time + cook_time (default cook_time to 0 if undefined) const computedTotalTime = values.prep_time + (values.cook_time ?? 0); const recipePayload = { ...recipeData, total_time: computedTotalTime, ingredients: values.ingredients as unknown as Json, directions: values.directions as unknown as Json, notes: values.notes as unknown as Json, images: imageUrls, }; try { const recipeDataResponse = await mutateAsync(recipePayload); const newRecipe = Array.isArray(recipeDataResponse) ? recipeDataResponse[0] : recipeDataResponse; if (categories.length > 0 && newRecipe?.id) { await insertRecipeCategories(newRecipe.id, categories); } reset(); router.push(`/recipe_page?id=${newRecipe?.id}`); } catch (error) { console.error('Error inserting recipe or categories:', error); alert('Failed to insert recipe'); } }; return ( <AuthenticatedPage> <div className='max-w-3xl mx-auto mt-10 p-6 bg-white text-gray-700 rounded shadow'> <div className='flex justify-between items-center mb-6'> <Link href='/home_page' className='border border-violet-300 bg-white text-gray-800 hover:bg-violet-300 hover:text-gray-800 transition-colors rounded-xl flex items-center justify-center px-4 h-10' > Back </Link> <h2 className='text-2xl font-bold text-center flex-1'> Update Recipe </h2> </div> <form onSubmit={handleSubmit(onSubmit)} className='space-y-4'> <TextInput label='Recipe Name' placeholder='Enter recipe name' {...register('name', { required: true })} required variant='filled' className='w-full' /> {/* Difficulty Section */} <div className='mt-4'> <label className='block text-sm font-medium text-gray-700 mb-2'> Difficulty </label> <div className='flex space-x-4'> {[0, 1, 2].map((level) => ( <button key={level} type='button' className={`flex-1 py-2 rounded-md text-black ${ difficulty === level ? 'bg-violet-300' : 'border bg-slate-200 hover:bg-slate-300' }`} onClick={() => handleDifficultyChange(level)} > {['Easy', 'Medium', 'Hard'][level]} </button> ))} </div> </div> <Controller control={control} name='prep_time' rules={{ required: true }} render={({ field: { value, onChange } }) => ( <NumberInput label='Prep Time (minutes)' placeholder='Prep time' value={value} onChange={onChange} required variant='filled' className='w-full' /> )} /> <Controller control={control} name='cook_time' render={({ field: { value, onChange } }) => ( <NumberInput label='Cook Time (minutes)' placeholder='Cook time' value={value} onChange={onChange} variant='filled' className='w-full' /> )} /> <Controller control={control} name='servings' render={({ field: { value, onChange } }) => ( <NumberInput label='Servings' placeholder='Servings' value={value} onChange={onChange} variant='filled' className='w-full' /> )} /> <Controller control={control} name='shared' render={({ field }) => ( <Switch label='Shared' checked={field.value} onChange={(event) => field.onChange(event.currentTarget.checked) } color={'#DBCDF0'} /> )} /> {/* MultiSelect for Categories */} <Controller control={control} name='categories' render={({ field }) => ( <MultiSelect label='Categories' placeholder={ categoriesLoading ? 'Loading categories...' : 'Select categories' } data={categoryOptions} value={field.value.map(String)} onChange={(values) => field.onChange(values.map(Number))} searchable nothingFoundMessage='No categories found' className='w-full' disabled={categoriesLoading} /> )} /> {/* Label and File input for images */} <div className='flex flex-col'> <label className='mb-1 font-medium'>Recipe Images</label> <Controller control={control} name='images' render={({ field: { onChange, ref } }) => ( <input type='file' multiple accept='image/*' onChange={(e) => onChange(e.target.files)} ref={ref} title='Upload Images' className='block w-full text-sm text-gray-500 file:mr-4 file:py-2 file:px-4 file:rounded file:border-0 file:text-sm file:font-semibold file:bg-violet-200 file:text-gray-800 hover:file:bg-violet-100' /> )} /> </div> {/* Structured Ingredients */} <div className='border p-4 rounded'> <h3 className='font-bold mb-2'>Ingredients</h3> {ingredientFields.map((field, index) => ( <div key={field.id} className='flex gap-2 mb-2' > <TextInput placeholder='Name' {...register(`ingredients.${index}.name` as const, { required: true, })} className='flex-1' /> <Controller control={control} name={`ingredients.${index}.amount` as const} rules={{ required: true }} render={({ field: { value, onChange } }) => ( <NumberInput placeholder='Amount' value={value} onChange={onChange} className='w-24' /> )} /> <TextInput placeholder='Unit' {...register(`ingredients.${index}.unit` as const, { required: true, })} className='w-24' /> <Button color='red' onClick={() => removeIngredient(index)} > Remove </Button> </div> ))} <button type='button' className='bg-slate-200 text-black rounded-md hover:bg-slate-100 transition-all flex items-center justify-center px-4 h-10' onClick={() => appendIngredient({ name: '', amount: 0, unit: '' }) } > Add Ingredient </button> </div> {/* Structured Directions */} <div className='border p-4 rounded'> <h3 className='font-bold mb-2'>Directions</h3> {directionFields.map((field, index) => ( <div key={field.id} className='flex gap-2 mb-2' > <Textarea placeholder={`Step ${index + 1}`} {...register(`directions.${index}.instruction` as const, { required: true, })} className='flex-1' /> <Button color='red' onClick={() => removeDirection(index)} > Remove </Button> </div> ))} <button type='button' className='bg-slate-200 text-black rounded-md hover:bg-slate-100 transition-all flex items-center justify-center px-4 h-10' onClick={() => appendDirection({ instruction: '' })} > Add Direction </button> </div> {/* Structured Notes */} <div className='border p-4 rounded'> <h3 className='font-bold mb-2'>Notes</h3> {noteFields.map((field, index) => ( <div key={field.id} className='flex gap-2 mb-2' > <Textarea placeholder={`Note ${index + 1}`} {...register(`notes.${index}.note` as const, { required: true, })} className='flex-1' /> <Button color='red' onClick={() => removeNote(index)} > Remove </Button> </div> ))} <button type='button' className='bg-slate-200 text-black rounded-md hover:bg-slate-100 transition-all flex items-center justify-center px-4 h-10' onClick={() => appendNote({ note: '' })} > Add Note </button> </div> <button type='submit' className={`rounded-xl transition-colors flex items-center justify-center text-sm h-10 w-full px-4 bg-violet-300 text-black ${ isPending ? 'opacity-50 cursor-not-allowed' : 'hover:bg-white hover:border hover:border-violet-400' }`} disabled={isPending} // Disable button when loading > {isPending ? 'Loading...' : 'Insert Recipe'} </button> </form> </div> </AuthenticatedPage> ); } export default UpdateRecipeClient;Key Changes Made:
-
Logging Fetched Data: Adding a
console.logstatement to show therecipeDatafetched from the database helps identify structural issues. -
Parsing Ingredients and Directions: Ensure that ingredients and directions are parsed correctly from their stored format. If they come as JSON strings, you should JSON parse them, as shown in the adjusted code.
-
Checking Data Structure: Using the logged data, verify that each property in
recipeDataexists and that the object keys match what your form expects.
Make sure to observe the console logs when the component is rendered. This will provide insight into whether the correct data is being fetched and utilized. If you see that the recipe data appears correctly in the console but is not populating the fields, double-check the field names in your state management and the fields you are binding to in the form.
If it still doesn't work after these checks, please share the structure of the
recipeDatayou see in the logs. This will help determine how to adjust the mappings accordingly. - Check Fetch Data Structure: Ensure that the fetched