How to handle CRUD in a form component

CRUD is an acronym for the four basic functionalities a model should be able to do in order to be complete: create, read, update, and delete. It is commonly used while making web applications because its a concrete framework for the developer to remember while creating each model.

CRUD operations
CRUD operations

What is a form component?

A form component is used to interact with the user on the application interface. It collects the information from the end user as input which is used to manipulate data in the model. Moreover, it helps the developer understand which input type and widget is required to enter the information.

Example

Let's see a React.js application for a to-do list model that allows the user to create, read, update, and remove tasks.

import { useState } from "react"
import Button from "./Button";

const AddTask = ({onAdd}) => {

    const [text , setText] = useState('')
    const [date , setDate] = useState('')
    const [time , setTime] = useState('')

    const onSubmit = (e) => {
        e.preventDefault()

        if(!text) { 
            alert("Kindly Fill Text Field") 
            return
        }
        
        onAdd({text , date , time});
        setText('');
        setDate('');
        setTime('');
    }

    const onPress = () => {
        alert("Your request is recorded");
    }

    return (
        <form className = "myform" onSubmit = {onSubmit}>
           <div>
            <label>Task: </label>
            <input type = "text" placeholder="Enter your Task here" value = {text} onChange={(e) => setText(e.target.value)}/>

            <label>Date: </label>
            <input type = "date" placeholder="Enter the Date" value = {date} onChange={(e) => setDate(e.target.value)}/>

            <label>Time: </label>
            <input type = "time" placeholder="Enter the Time" value = {time} onChange={(e) => setTime(e.target.value)}/>
           
            <div className = 'submit'>
            <Button text = "Submit" action = {() => onPress()}/>
            </div>
           </div> 
        </form>
    )
}
export default AddTask
CRUD operations for a to do list.

How is CRUD implemented in the example?

This is the main interface for the created to-do list that displays the existing task and buttons to perform all CRUD operations. Let's check the functionality of each CRUD operation one by one.

A to-do list implementing all CRUD operations.
A to-do list implementing all CRUD operations.

Create

The create operation allows the user to add new data to their model. For example, we can add a new item to the to-do list by entering the information in the form.

In this application, when the Add Item button is clicked, a form prompts in the to-do list. AddTasks.js component prints the input form where we can add the name, date, and time of the new item. Click submit to create the new task once the required information is given.

Task 4 is created.
Task 4 is created.

Add function, in the App.js, takes the newly created task as a parameter, and adds that task to the tasks array.

//Add Task
const Add = (task) => {
const id = 5;
const newTask = {id, ...task}
setTasks([...tasks, newTask])
}

Read

The read operation allows the user to view the existing data inside the model. This is the most crucial operation from the user's perspective because it enables them to see the response to their actions on the interface.

All the existing tasks in the to-do list model are printed on the screen.

Task 4 can be read along with all the other tasks.
Task 4 can be read along with all the other tasks.

Task.js component calls a map function that one by one prints all the tasks in the tasks array by sending the content of each task to the OneTask.js component.

//Map acts as a loop for printing all tasks
const Task = ({tasks , onDelete , onUpdate}) => {
return(
<>
{tasks.map((mytask) =>(
<OneTask key = {mytask.id} task = {mytask} onDelete = {onDelete} onUpdate = {onUpdate}/>
))}
</>
)
}

Update

The update operation allows the user to edit the information of a pre-existing date inside the model.

In this application, the user can update the name of the task by entering the new name in the input field and clicking the Update Item button. For example, the name of Task 4 is updated to the new name given in the input field i.e. Task 4.1.

Task 4 name is updated to Task 4.1.
Task 4 name is updated to Task 4.1.

onUpdate function, in the App.js, takes the text added in the input field and the id of the corresponding task. A map is used to iterate the tasks array to search the task that is to be updated through its id. Once the task is found, it's existing text is replaced with the newtxt sent as a parameter. The updated task is then set in the tasks array.

//Update Task
const onUpdate = (id, newtxt) => {
const updatedTasks = tasks.map((task) => {
if (task.id === id) {
return {...task, text: newtxt};
}
return task;
});
setTasks(updatedTasks);
}

Delete

The delete operation allows the user to remove existing data from the model.

In this application, the user can remove the task from the tasks array by clicking the Remove Item button. For example, Task 4.1 is removed from the list of tasks, and all the other tasks in the array are displayed.

Task 4.1 is deleted.
Task 4.1 is deleted.

Remove function in App.js takes the id of the task that is to be removed as a parameter and implements a filter to remove the task. It iterates the tasks array and compares the id of the tasks with the sent tasks. All the tasks are set in the array except for the task with the id sent in the parameter.

//Remove Task
const Remove = (id) => {
setTasks(tasks.filter((task) => task.id !== id))
}

Test your understanding

Question

How to identify which data is being manipulated through CRUD operations?

Show Answer

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved