import { useEffect, useState } from 'react' import { api } from '../lib/api.js' export default function Recipes() { const [mine, setMine] = useState([]) const [catalog, setCatalog] = useState([]) const [restrictions, setRestrictions] = useState([]) const [detail, setDetail] = useState(null) const [error, setError] = useState(null) const [form, setForm] = useState({ name: '', guide: '', servings: 4, restrictionIds: [] }) const [lines, setLines] = useState([{ ingredientName: '', quantity: '' }]) const load = () => api.get('/recipes/mine').then(setMine).catch(e => setError(e.message)) useEffect(() => { load() api.get('/catalog/ingredients').then(setCatalog).catch(() => {}) api.get('/catalog/restrictions').then(setRestrictions).catch(() => {}) }, []) const setLine = (i, key) => (e) => { const copy = [...lines] copy[i] = { ...copy[i], [key]: e.target.value } setLines(copy) } const create = async () => { setError(null) try { const body = { name: form.name, guide: form.guide, servings: Number(form.servings), ingredients: lines .filter(l => l.ingredientName && l.quantity) .map(l => ({ ingredientName: l.ingredientName, quantity: Number(l.quantity) })), restrictionIds: form.restrictionIds.map(Number) } const created = await api.post('/recipes', body) setDetail(created) setForm({ name: '', guide: '', servings: 4, restrictionIds: [] }) setLines([{ ingredientName: '', quantity: '' }]) load() } catch (e) { setError(e.message) } } const share = async (id) => { setError(null) try { await api.post('/posts', { recipeId: id, isPrivate: false, isFavourite: false, status: 'published' }) alert('Shared to the feed') } catch (e) { setError(e.message) } } return (
{error &&
{error}
}

New recipe

Energy is not entered: the server sums it from the ingredients and divides by servings.

setForm({ ...form, name: e.target.value })} />