Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
126 changes: 77 additions & 49 deletions src/Component/TodoList.js
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
import React, { useState, useEffect } from 'react';
import { ToastContainer, toast } from 'react-toastify';
import 'react-toastify/dist/ReactToastify.css';
import './style.css';
import todoImage from "../image/todo.png"
import React, { useState, useEffect } from "react";
import { ToastContainer, toast } from "react-toastify";
import "react-toastify/dist/ReactToastify.css";
import "./style.css";
import todoImage from "../image/todo.png";

const TodoList = () => {
// State variables
const [tasks, setTasks] = useState([]); // Holds the list of tasks
const [inputValue, setInputValue] = useState(''); // Holds the value of the input field
const [filter, setFilter] = useState('all'); // Holds the current filter type
const [inputValue, setInputValue] = useState(""); // Holds the value of the input field
const [filter, setFilter] = useState("all"); // Holds the current filter type
const [isLoading, setIsLoading] = useState(true); // Indicates whether the data is being loaded
const [editTaskId, setEditTaskId] = useState(null); // Holds the ID of the task being edited

Expand All @@ -20,12 +20,14 @@ const TodoList = () => {
// Fetch todos from an API
const fetchTodos = async () => {
try {
const response = await fetch('https://jsonplaceholder.typicode.com/todos?_limit=4');
const response = await fetch(
"https://jsonplaceholder.typicode.com/todos?_limit=4",
);
const todos = await response.json();
setTasks(todos);
setIsLoading(false);
} catch (error) {
console.log('Error fetching todos:', error);
console.log("Error fetching todos:", error);
setIsLoading(false);
}
};
Expand All @@ -37,46 +39,53 @@ const TodoList = () => {

// Add a new task
const handleAddTask = async () => {
if (inputValue.trim() === '') {
if (inputValue.trim() === "") {
return;
}

const newTask = {
title: inputValue,
completed: false
completed: false,
};

try {
const response = await fetch('https://jsonplaceholder.typicode.com/todos', {
method: 'POST',
body: JSON.stringify(newTask),
headers: {
'Content-type': 'application/json; charset=UTF-8',
const response = await fetch(
"https://jsonplaceholder.typicode.com/todos",
{
method: "POST",
body: JSON.stringify(newTask),
headers: {
"Content-type": "application/json; charset=UTF-8",
},
},
});
);
const addedTask = await response.json();
setTasks((prevTasks) => [...prevTasks, addedTask]);
setInputValue('');
toast.success('Task added successfully');
const taskWithUniqueId = {
...addedTask,
id: Date.now(),
};
setTasks((prevTasks) => [...prevTasks, taskWithUniqueIdha]);
setInputValue("");
toast.success("Task added successfully");
} catch (error) {
console.log('Error adding task:', error);
toast.error('Error adding task');
console.log("Error adding task:", error);
toast.error("Error adding task");
}
};

// Handle checkbox change for a task
const handleTaskCheckboxChange = (taskId) => {
setTasks((prevTasks) =>
prevTasks.map((task) =>
task.id === taskId ? { ...task, completed: !task.completed } : task
)
task.id === taskId ? { ...task, completed: !task.completed } : task,
),
);
};

// Delete a task
const handleDeleteTask = (taskId) => {
setTasks((prevTasks) => prevTasks.filter((task) => task.id !== taskId));
toast.success('Task deleted successfully');
toast.success("Task deleted successfully");
};

// Edit a task
Expand All @@ -88,42 +97,47 @@ const TodoList = () => {

// Update a task
const handleUpdateTask = async () => {
if (inputValue.trim() === '') {
if (inputValue.trim() === "") {
return;
}

const updatedTask = {
title: inputValue,
completed: false
completed: false,
};

try {
const response = await fetch(`https://jsonplaceholder.typicode.com/todos/${editTaskId}`, {
method: 'PUT',
body: JSON.stringify(updatedTask),
headers: {
'Content-type': 'application/json; charset=UTF-8',
const response = await fetch(
`https://jsonplaceholder.typicode.com/todos/${editTaskId}`,
{
method: "PUT",
body: JSON.stringify(updatedTask),
headers: {
"Content-type": "application/json; charset=UTF-8",
},
},
});
);
const updatedTaskData = await response.json();
setTasks((prevTasks) =>
prevTasks.map((task) =>
task.id === editTaskId ? { ...task, title: updatedTaskData.title } : task
)
task.id === editTaskId
? { ...task, title: updatedTaskData.title }
: task,
),
);
setInputValue('');
setInputValue("");
setEditTaskId(null);
toast.success('Task updated successfully');
toast.success("Task updated successfully");
} catch (error) {
console.log('Error updating task:', error);
toast.error('Error updating task');
console.log("Error updating task:", error);
toast.error("Error updating task");
}
};

// Mark all tasks as completed
const handleCompleteAll = () => {
setTasks((prevTasks) =>
prevTasks.map((task) => ({ ...task, completed: true }))
prevTasks.map((task) => ({ ...task, completed: true })),
);
};

Expand All @@ -139,11 +153,11 @@ const TodoList = () => {

// Filter tasks based on the selected filter
const filteredTasks = tasks.filter((task) => {
if (filter === 'all') {
if (filter === "all") {
return true;
} else if (filter === 'completed') {
} else if (filter === "completed") {
return task.completed;
} else if (filter === 'uncompleted') {
} else if (filter === "uncompleted") {
return !task.completed;
}
return true;
Expand Down Expand Up @@ -173,8 +187,11 @@ const TodoList = () => {
value={inputValue}
onChange={handleInputChange}
/>
<button id="btn" onClick={editTaskId ? handleUpdateTask : handleAddTask}>
{editTaskId ? 'Update' : 'Add'}
<button
id="btn"
onClick={editTaskId ? handleUpdateTask : handleAddTask}
>
{editTaskId ? "Update" : "Add"}
</button>
</div>

Expand Down Expand Up @@ -222,21 +239,32 @@ const TodoList = () => {
<div className="dropdown">
<button className="dropbtn">Filter</button>
<div className="dropdown-content">
<a href="#" id="all" onClick={() => handleFilterChange('all')}>
<a href="#" id="all" onClick={() => handleFilterChange("all")}>
All
</a>
<a href="#" id="rem" onClick={() => handleFilterChange('uncompleted')}>
<a
href="#"
id="rem"
onClick={() => handleFilterChange("uncompleted")}
>
Uncompleted
</a>
<a href="#" id="com" onClick={() => handleFilterChange('completed')}>
<a
href="#"
id="com"
onClick={() => handleFilterChange("completed")}
>
Completed
</a>
</div>
</div>

<div className="completed-task">
<p>
Completed: <span id="c-count">{tasks.filter((task) => task.completed).length}</span>
Completed:{" "}
<span id="c-count">
{tasks.filter((task) => task.completed).length}
</span>
</p>
</div>
<div className="remaining-task">
Expand Down