From 7ca504354b9bb50c6b02a7a0143d8755dd42424b Mon Sep 17 00:00:00 2001 From: Liz <96144994+lizferreira@users.noreply.github.com> Date: Mon, 3 Jun 2024 16:58:43 -0400 Subject: [PATCH] Update App.js --- todo_list/src/App.js | 113 +++++++++++++++++++++++++++++++++++++++---- 1 file changed, 104 insertions(+), 9 deletions(-) diff --git a/todo_list/src/App.js b/todo_list/src/App.js index 220a997d1c..2c73cac02f 100644 --- a/todo_list/src/App.js +++ b/todo_list/src/App.js @@ -1,27 +1,122 @@ -import React, {useState} from "react"; +import React, {useState, useEffect} from "react"; import "./App.css"; const App = () => { const [todos, setTodos] = useState([]); + + const [todoEditing, setTodoEditing] = useState(null); + + useEffect(() => { + const json = localStorage.getItem("todos"); + const loadedTodos = JSON.parse(json); + if (loadedTodos){ + setTodos(loadedTodos); + } + }, []); + + useEffect(() => { + if (todos.length > 0){ + const json = JSON.stringify(todos); + localStorage.setItem("todos", json); + } + }, [todos]); // Add the handlesubmit code here - + function handleSubmit(e){ + e.preventDefault(); + + let todo = document.getElementById('todoAdd').value + const newtodo = { + id: new Date().getTime(), + text: todo.trim(), + completed: false, + }; + + if (newtodo.text.length > 0){ + setTodos([...todos].concat(newtodo)); + } + else{ + alert("Enter Valid Task"); + } + document.getElementById('todoAdd').value = "" + } // Add the deleteToDo code here - +function deleteTodo(id){ + let updateTodos = [...todos].filter((todo) => todo.id !==id); + setTodos(updateTodos); +} // Add the toggleComplete code here +function toggleComplete(id){ + let updateTodos = [...todos].map((todo) => { + if(todo.id === id){ + todo.completed = !todo.completed; + } + return todo; + }); + setTodos(updateTodos); +} // Add the submitEdits code here +function submitEdits(newtodo){ + const updateTodos = [...todos].map((todo) => { + if(todo.id === newtodo.id){ + todo.text = document.getElementById(newtodo.id).value; + } + return todo; + }); + setTodos(updateTodos); + setTodoEditing(null); +} + return( -
-

Todo List

-
- - -
+
+

Todo List

+
+ + + +
+ {todos.map((todo) => ( + +
+
+ toggleComplete(todo.id)} + /> + + {todo.id === todoEditing ? + () : + (
{todo.text}
) + } +
+ +
+ {todo.id === todoEditing? + ( + + ): + ( + + )} + + +
+
+))}
); };