import { useContext, useState } from 'react'; import { MessageContext } from '../UserMessage'; import { Item } from './Item'; import { addItem } from './item-service'; /** * Stateful form component for creating a new Item. */ export function ItemForm(props: { onSubmit?: (item: Item) => void }) { const messageContext = useContext(MessageContext); // create state for each of our form fields const [description, setDescription] = useState(''); const [done, setDone] = useState(false); /** * Private submit function for when the user submits the form. */ async function onSubmit() { // notice that we can use async/await with try-catch to handle asynchronous errors just like synchronous ones try { const createdItem = await addItem({ description, done }); clearForm(); messageContext.updateMessage({ type: 'success', text: 'Added todo item', show: true, }); // call passed in handler from parent component, if one was provided props.onSubmit?.(createdItem); } catch (e) { messageContext.updateMessage({ type: 'error', text: `Error adding todo item: ${e}`, show: true, }); } } /** * Private clear function for when the user cancels the form. */ function clearForm() { setDescription(''); setDone(false); } return ( <>

Add Task

{/* most of these attributes are hints for our CSS library, not React. i.e. only value and onChange have anything to do with React because we are binding their values to JS with brackets */} setDescription(e.target.value)} /> setDone(!done)} />
); }