import { useEffect, useState } from 'react'
import { api } from '../lib/api.js'
export default function Grocery() {
const [lists, setLists] = useState([])
const [recipes, setRecipes] = useState([])
const [catalog, setCatalog] = useState([])
const [open, setOpen] = useState(null)
const [error, setError] = useState(null)
const [notes, setNotes] = useState('')
const [bulk, setBulk] = useState([])
const [item, setItem] = useState({ ingredientName: '', buyQuantity: '' })
const load = () => api.get('/grocery-lists').then(setLists).catch(e => setError(e.message))
useEffect(() => {
load()
api.get('/recipes').then(setRecipes).catch(() => {})
api.get('/catalog/ingredients').then(setCatalog).catch(() => {})
}, [])
const create = async () => {
setError(null)
try {
const created = await api.post('/grocery-lists', {
notes,
bulkRecipeIds: bulk.map(Number),
singleItems: item.ingredientName && item.buyQuantity
? [{ ingredientName: item.ingredientName, buyQuantity: Number(item.buyQuantity) }]
: []
})
setOpen(created)
setNotes(''); setBulk([]); setItem({ ingredientName: '', buyQuantity: '' })
load()
} catch (e) { setError(e.message) }
}
return (
{error &&
{error}
}
{open && (
Shopping list #{open.id}
{open.notes} · total {open.kcal} kcal
{open.bulkRecipes.length > 0 && <> · from: {open.bulkRecipes.join(', ')}>}
| category | ingredient | grams |
{open.shoppingLines.map(l => (
| {l.category} |
{l.ingredient} |
{l.totalGrams} |
))}
)}
My lists
{lists.map(l => (
| {new Date(l.dateTime).toLocaleDateString()} |
{l.notes} |
{l.kcal} kcal |
{l.bought ? 'bought' : 'open'} |
|
))}
)
}