import { useAuthContext } from "../../context/AuthContext"; import { useCallback, useEffect, useState } from "react"; import { Button, Card, Divider, Page, Panel } from "../ui" import { DropdownData, IIngredient, IRecipe } from "../../schemas"; import API from "../../util/API"; import { useSelectorContext } from "../../context/SelectorContext"; import IngredientSelector from "../derived/IngredientSelector"; import { v4 } from "uuid"; const AddRecipe = () => { const { user, token } = useAuthContext(); const { data, setData } = useSelectorContext(); const [input, setInput] = useState({ name: '', preptime: '', description: '', authoruserid: '' }) const [measurements, setMeasurements] = useState([]); const [ingredientFields, setIngredientFields] = useState>([]); const [optionCount, setOptionCount] = useState(0); const [toast, setToast] = useState(<>) // store all ingredients on page mount useEffect(() => { token && (async() => { const ingredients = new API.Ingredient(token); const _measurements = new API.Measurements(token); const result = await ingredients.getAll(); const measurementList = await _measurements.getAll(); if (result) { setData((prev) => [...prev, ...result]); } if (measurementList) { setMeasurements((prev) => [...prev, ...measurementList]); } })(); }, [token]) useEffect(() => { if (data.length && measurements.length) { setIngredientFields([]); } }, [data, measurements]) // once user information is available, store it in recipe data useEffect(() => { if (!user) return; user && setInput((prev: IRecipe) => { return { ...prev, authoruserid: user.id! } }) }, [user]) // submit handler const handleCreate = async () => { if (!token) return; for (let field of Object.keys(input)) { if (!input[field as keyof IRecipe]) { return; } } const recipe = new API.Recipe(token); const result = await recipe.post(input); const recipeID = result.recipe.id; const recipeName = result.recipe.name; setToast(

Created recipe {recipeName} successfully!

View your new recipe here!

) } const destroySelector = useCallback((position: number) => { setIngredientFields((prev) => { const newState = new Array(); for (let i = 0; i < prev.length; i++) { if (i === position) { continue; } else { newState.push(prev[i]); } } return newState; }) }, [ingredientFields]); function handleNewOption() { setIngredientFields((prev) => [...prev, ]) setOptionCount(prev => prev + 1); } return (

Add a New Recipe

setInput({ ...input, name: e.target.value })} />
setInput({ ...input, preptime: e.target.value })} />
{ data && (
{ ingredientFields }
)}
{ "description here" }
{ toast }
) } export default AddRecipe;