I'm currently learning hook, and I'm writing a todo-list:
import './App.css';
import React, {useState} from 'react';
import Item from './components/Item';
function App() {
const [tasks, setTasks] = useState([]);
const addTask = (e) => {
if(e.key === 'Enter'){
let newTask = {content: e.target.value, completed: false};
console.log(newTask);
setTasks(prevTask => {
return ([...prevTask, newTask]);
});
console.log(tasks);
}
}
const completeTask = (e) =>{
let newTask = tasks.slice();
newTask[e].completed = !tasks[e].completed;
setTasks(newTask);
}
const deleteTask = (e) => {
let newTask = tasks.slice();
newTask.splice(e);
setTasks(newTask);
}
return (
<>
<header className="todo-app__header">
<h1 className="todo-app__title">todos</h1>
</header>
<section className="todo-app__main">
<input className="todo-app__input" placeholder="What needs to be done?" onKeyDown={addTask}/>
<ul className="todo-app__list" id="todo-list">
{tasks.map(item => <Item num = {tasks.indexOf(item)} text={item.content} completed = {item.completed}
onClick = {completeTask(tasks.indexOf(item))} delete = {deleteTask(tasks.indexOf(item))}/>)}
</ul>
</section>
</>
);
}
export default App;
However, adding tasks is not working!! The newTask printed is well, but it doesn't push into the tasks array. The tasks is still empty.
What's the problem?
Also, another problem: is it related to useeffect? I don't know what useeffect is used for.