Inserting Data
First, let’s add the React code for adding a new task.
Code Explanation
- We added a state variable
newTaskTitle
to store the title of the new task being added. - We defined the
addTask
function, 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.
Code Explanation
- We added a form element with an
onSubmit
handler that calls theaddTask
function when the form is submitted. - Inside the form, we added an input element bound to the
newTaskTitle
state variable. TheonChange
handler updates thenewTaskTitle
state as the user types. - We added a button to submit the form.
Now let’s call Remult to insert the new task.
Code Explanation
- We used the
taskRepo.insert
method to insert a new task with the title stored innewTaskTitle
. This makes a REST APIPOST
call to the backend to insert the new task into the database. - If the task is successfully inserted, we update the
tasks
state with the new task and clear thenewTaskTitle
input 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