Untitled
unknown
plain_text
2 years ago
4.3 kB
8
Indexable
import { useState } from "react";
const AddTodo = () => {
const initialData = {
title: "",
status: "Not-Completed",
};
const [formData, setFormData] = useState(initialData);
const [todos, setTodos] = useState([]);
const [isEditing, setIsEditing] = useState(false);
const [editingIndex, setEditingIndex] = useState(null);
const handleInputChange = (e) => {
setFormData({ ...formData, [e.target.name]: e.target.value });
};
//add todo
const handleFormSubmit = (e) => {
e.preventDefault();
const newForm = {
title: formData.title,
status: formData.status,
};
setTodos([...todos, newForm]);
// console.log(newForm, "New Form to be sent");
setFormData(initialData);
};
//delete
const handleDelete = (index) => {
console.log("buttonDelete");
const filteredElement = todos.filter((ele, idx) => idx !== index);
setTodos(filteredElement);
};
//toggle status
const handleToggle = (index) => {
const updatedTodos = [...todos];
updatedTodos[index].status =
updatedTodos[index].status === "Not-Completed"
? "Completed"
: "Not-Completed";
setTodos(updatedTodos);
};
console.log(todos, "Todos to be sent");
//edit the title of the todo
const handleUpdate = (index) => {
setIsEditing(true);
setEditingIndex(index);
setFormData({
...formData,
title: todos[index].title
})
};
const handleEditFormSubmit=(e)=>{
e.preventDefault();
const updatedTodos = [...todos];
updatedTodos[editingIndex].title = formData.title;
setTodos(updatedTodos);
setEditingIndex(false);
setFormData(initialData);
setEditingIndex(null)
}
return (
<>
<h2>ADD TODO</h2>
{isEditing ? (
<form onSubmit={handleEditFormSubmit}>
<label>
Edit the title:{" "}
<input
type="text"
name="title"
placeholder="Title"
value={formData.title}
onChange={handleInputChange}
/>{" "}
</label>
<br />
<input type="submit"></input>
</form>
) : (
<form className="add-todo" onSubmit={handleFormSubmit}>
<label>
Add the title:{" "}
<input
type="text"
name="title"
placeholder="Title"
value={formData.title}
onChange={handleInputChange}
/>{" "}
</label>
<br />
<input type="submit"></input>
</form>
)}
<ul>
{todos.map((ele, index) => (
<li key={index}>
<div
style={{
border: "2px solid white",
marginTop: "10px",
padding: "10px",
backgroundColor:
ele.status === "Not-Completed" ? "red" : "green",
}}
onClick={(e) => handleToggle(index)}
>
<p>Title: {ele.title}</p>
<p>Status: {ele.status}</p>
<p>
Created At: {new Date().toLocaleDateString()}{" "}
{new Date().toLocaleTimeString()}
</p>
<button
onClick={(e) => {
handleDelete(index);
e.stopPropagation();
}}
>
DELETE
</button>
<button
onClick={(e) => {
handleUpdate(index);
e.stopPropagation();
}}
>
UPDATE
</button>
</div>
</li>
))}
</ul>
</>
);
};
export default AddTodo;
{
/* <input
type="radio"
name="status"
value="true"
onChange={handleInputChange}
/>
Completed
<input
type="radio"
name="status"
value="false"
onChange={handleInputChange}
/>
Not-Completed
<br /> */
}
Editor is loading...
Leave a Comment