DEV Community

Cover image for Mastering CRUD Operations in JavaScript: Building a To-Do App.๐Ÿš€
Dharmendra Kumar
Dharmendra Kumar

Posted on

Mastering CRUD Operations in JavaScript: Building a To-Do App.๐Ÿš€

CRUD operations are the backbone of many applications, allowing you to create, read, update, and delete data. Understanding how CRUD works in JavaScript can empower you to build robust, interactive web applications. Let's dive into what CRUD is, why itโ€™s essential, and how to implement it in a simple To-Do app using HTML, CSS, and JavaScript.

What is CRUD?

CRUD stands for Create, Read, Update, and Delete. These are the four basic operations you can perform on data in a database or any storage system.

  1. Create: Add new data
  2. Read: Retrieve existing data
  3. Update: Modify existing data
  4. Delete: Remove data

Why CRUD?

CRUD operations are fundamental because they provide a consistent way to manage data. Whether you're building a small application or a large-scale system, CRUD operations ensure you can effectively interact with your data.

Using CRUD

Implementing CRUD operations in JavaScript helps in managing the state of your application and ensures seamless data manipulation.

Building a To-Do App with CRUD Operations

We'll build a simple To-Do app to demonstrate CRUD operations. This app will allow users to add tasks, view tasks, edit tasks, and delete tasks.

todo app

Setting Up the HTML

First, we need a basic HTML structure for our app.



<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>To-Do App</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div class="container">
<h1>To-Do List</h1>
<input type="text" id="taskInput" placeholder="Add a new task">
<button onclick="createTask()">Add Task</button>
<ul id="taskList"></ul>
</div>
<script src="script.js"></script>
</body>
</html>

Enter fullscreen mode Exit fullscreen mode




Adding Some CSS

Next, let's style our app with some basic CSS.



/* styles.css */
body {
font-family: Arial, sans-serif;
background-color: #f4f4f4;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}

.container {
background: white;
padding: 20px;
border-radius: 8px;
box-shadow: 0 2px 5px rgba(0,0,0,0.1);
}

input, button {
margin: 10px 0;
padding: 10px;
border-radius: 4px;
border: 1px solid #ddd;
}

ul {
list-style-type: none;
padding: 0;
}

li {
padding: 10px;
margin: 5px 0;
background: #f9f9f9;
border-radius: 4px;
display: flex;
justify-content: space-between;
align-items: center;
}

Enter fullscreen mode Exit fullscreen mode




Implementing CRUD Operations in JavaScript

Finally, let's add the JavaScript code to handle our CRUD operations.



// script.js

// Initialize an empty array to store tasks
let tasks = [];

// Create operation: Add a new task
function createTask() {
const taskInput = document.getElementById('taskInput');
const task = taskInput.value;
if (task) {
tasks.push({ id: Date.now(), name: task });
taskInput.value = '';
renderTasks();
}
}

// Read operation: Display tasks
function renderTasks() {
const taskList = document.getElementById('taskList');
taskList.innerHTML = ''; // Clear the current list
tasks.forEach(task => {
const li = document.createElement('li');
li.innerHTML =
&lt;span&gt;</span><span class="p">${</span><span class="nx">task</span><span class="p">.</span><span class="nx">name</span><span class="p">}</span><span class="s2">&lt;/span&gt;
&lt;span&gt;
&lt;button onclick="editTask(</span><span class="p">${</span><span class="nx">task</span><span class="p">.</span><span class="nx">id</span><span class="p">}</span><span class="s2">)"&gt;Edit&lt;/button&gt;
&lt;button onclick="deleteTask(</span><span class="p">${</span><span class="nx">task</span><span class="p">.</span><span class="nx">id</span><span class="p">}</span><span class="s2">)"&gt;Delete&lt;/button&gt;
&lt;/span&gt;
;
taskList.appendChild(li);
});
}

// Update operation: Edit a task
function editTask(id) {
const newTaskName = prompt("Enter the new task name:");
if (newTaskName) {
tasks = tasks.map(task => task.id === id ? { ...task, name: newTaskName } : task);
renderTasks();
}
}

// Delete operation: Remove a task
function deleteTask(id) {
tasks = tasks.filter(task => task.id !== id);
renderTasks();
}

// Initial rendering of tasks
renderTasks();

Enter fullscreen mode Exit fullscreen mode




In-Depth Explanation

Create

  • Function: createTask()
  • Description: Adds a new task to the tasks array.
  • Example: User types a task and clicks "Add Task". The task is added to the array and displayed in the list.

Read

  • Function: renderTasks()
  • Description: Displays all tasks in the tasks array.
  • Example: Each task is rendered as a list item with "Edit" and "Delete" buttons.

Update

  • Function: editTask(id)
  • Description: Edits an existing task.
  • Example: User clicks "Edit", enters a new task name, and the task is updated in the list.

Delete

  • Function: deleteTask(id)
  • Description: Deletes a task from the tasks array.
  • Example: User clicks "Delete" and the task is removed from the list.

Why CRUD is Essential

CRUD operations are essential for data management in applications. They provide a structured way to handle data, ensuring your application can interact with the data effectively and efficiently.

Use Cases of CRUD

  1. Web Applications: Managing user data, posts, comments, etc.
  2. Database Management: Performing operations on records in a database.
  3. APIs: Handling data sent to and received from client applications.

By understanding and implementing CRUD operations, you can build dynamic and interactive web applications that efficiently manage and manipulate data. This To-Do app is a simple yet powerful example of how CRUD operations work in practice. Happy coding!

Top comments (0)