Skip to content

Commit

Permalink
Update App.js
Browse files Browse the repository at this point in the history
  • Loading branch information
skllup7 committed Nov 3, 2022
1 parent bbbd673 commit f0d94c1
Showing 1 changed file with 10 additions and 99 deletions.
109 changes: 10 additions & 99 deletions todo_list/src/App.js
Original file line number Diff line number Diff line change
@@ -1,105 +1,16 @@
import React from "react";
import "./App.css";

const App = () => {
const [todos, setTodos] = React.useState([]);
const [todo, setTodo] = React.useState("");
const [todoEditing, setTodoEditing] = React.useState(null);
const [editingText, setEditingText] = React.useState("");

React.useEffect(() => {
const json = localStorage.getItem("todos");
const loadedTodos = JSON.parse(json);
if (loadedTodos) {
setTodos(loadedTodos);
}
}, []);

React.useEffect(() => {
const json = JSON.stringify(todos);
localStorage.setItem("todos", json);
}, [todos]);

function handleSubmit(e) {
e.preventDefault();

const newTodo = {
id: new Date().getTime(),
text: todo,
completed: false,
};
setTodos([...todos].concat(newTodo));
setTodo("");
}

function deleteTodo(id) {
let updatedTodos = [...todos].filter((todo) => todo.id !== id);
setTodos(updatedTodos);
}

function toggleComplete(id) {
let updatedTodos = [...todos].map((todo) => {
if (todo.id === id) {
todo.completed = !todo.completed;
}
return todo;
});
setTodos(updatedTodos);
}

function submitEdits(id) {
const updatedTodos = [...todos].map((todo) => {
if (todo.id === id) {
todo.text = editingText;
}
return todo;
});
setTodos(updatedTodos);
setTodoEditing(null);
}

return (
<div id="todo-list">
<h1>Todo List</h1>
<form onSubmit={handleSubmit}>
<input
type="text"
onChange={(e) => setTodo(e.target.value)}
value={todo}
/>
<button type="submit">Add Todo</button>
</form>
{todos.map((todo) => (
<div key={todo.id} className="todo">
<div className="todo-text">
<input
type="checkbox"
id="completed"
checked={todo.completed}
onChange={() => toggleComplete(todo.id)}
/>
{todo.id === todoEditing ? (
<input
type="text"
onChange={(e) => setEditingText(e.target.value)}
/>
) : (
<div>{todo.text}</div>
)}
</div>
<div className="todo-actions">
{todo.id === todoEditing ? (
<button onClick={() => submitEdits(todo.id)}>Submit Edits</button>
) : (
<button onClick={() => setTodoEditing(todo.id)}>Edit</button>
)}

<button onClick={() => deleteTodo(todo.id)}>Delete</button>
</div>
</div>
))}
</div>
);
return(
<div className ="App">
<h1>Todo List</h1>
<form>
<input type ="text" align ="right" />
<button type ="submit">Add Todo</button>
</form>
</div>
);
};

export default App;
export default App;

0 comments on commit f0d94c1

Please sign in to comment.