'use client'; import { useState } from 'react'; import { useRouter } from 'next/navigation'; import { fetchJson } from '../../../lib/api'; export default function CreateRecipePage() { const router = useRouter(); const [recipe, setRecipe] = useState({ name: '', description: '', instructions: '', ingredients: [{ productId: 0, quantity: '', unit: '', note: '' }], }); const [products, setProducts] = useState([]); const [isLoading, setIsLoading] = useState(false); const [error, setError] = useState(null); // Hämta produkter vid sidladdning useState(() => { fetchJson('/api/products') .then(setProducts) .catch(console.error); }, []); const handleIngredientChange = (index: number, field: string, value: string | number) => { const newIngredients = [...recipe.ingredients]; newIngredients[index] = { ...newIngredients[index], [field]: value }; setRecipe({ ...recipe, ingredients: newIngredients }); }; const addIngredient = () => { setRecipe({ ...recipe, ingredients: [...recipe.ingredients, { productId: 0, quantity: '', unit: '', note: '' }], }); }; const removeIngredient = (index: number) => { const newIngredients = [...recipe.ingredients]; newIngredients.splice(index, 1); setRecipe({ ...recipe, ingredients: newIngredients }); }; const handleSubmit = async (e: React.FormEvent) => { e.preventDefault(); setIsLoading(true); setError(null); // Konvertera quantity till number för varje ingrediens const recipeToSend = { ...recipe, ingredients: recipe.ingredients.map((ing) => ({ ...ing, quantity: Number(ing.quantity), })), }; try { const response = await fetch('/api/recipes', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(recipeToSend), }); if (!response.ok) { throw new Error('Kunde inte spara receptet'); } router.push('/recipes'); } catch (err) { setError((err as Error).message); } finally { setIsLoading(false); } }; return (

Lägg till nytt recept

{error &&

{error}

}