Inserting Data
First, let’s add the React code for adding a new task.
export function Todo() { const [tasks, setTasks] = useState<Task[]>([]); const [newTaskTitle, setNewTaskTitle] = useState(''); async function addTask(e: FormEvent) { e.preventDefault(); } useEffect(() => { taskRepo.find().then(setTasks); }, []);Code Explanation
- We added a state variable
newTaskTitleto store the title of the new task being added. - We defined the
addTaskfunction, which will handle the form submission. For now, it just prevents the default form submission behavior withe.preventDefault().
Next, let’s add the JSX for the form to input new tasks.
return ( <div> <h1>Todos</h1> <main> <form onSubmit={addTask}> <input value={newTaskTitle} placeholder="What needs to be done?" onChange={(e) => setNewTaskTitle(e.target.value)} /> <button>Add</button> </form> {tasks.map((task) => { return ( <div key={task.id}> <input type="checkbox" checked={task.completed} /> {task.title} </div> ) })} </main> </div>)Code Explanation
- We added a form element with an
onSubmithandler that calls theaddTaskfunction when the form is submitted. - Inside the form, we added an input element bound to the
newTaskTitlestate variable. TheonChangehandler updates thenewTaskTitlestate as the user types. - We added a button to submit the form.
Now let’s call Remult to insert the new task.
async function addTask(e: FormEvent) { e.preventDefault() try { const newTask = await taskRepo.insert({ title: newTaskTitle }) setTasks([...tasks, newTask]) setNewTaskTitle('') } catch (error: any) { alert((error as { message: string }).message) }}Code Explanation
- We used the
taskRepo.insertmethod to insert a new task with the title stored innewTaskTitle. This makes a REST APIPOSTcall to the backend to insert the new task into the database. - If the task is successfully inserted, we update the
tasksstate with the new task and clear thenewTaskTitleinput field. - If there’s an error, we display an alert with the error message.
This code results in the following REST API request to insert the new task:
POST /api/tasks
Try adding new tasks using the form in the preview window below.
Files
Preparing Environment
- Installing dependencies
- Starting http server