as in title. I am new in the react and I write simple todoApp. My App.js:
const App = () => {
const initTasks = [
{id: 1,text: 'Task1'},
{id: 2,text: "Task2"},
{id: 3,text: "Task3"}]
const [tasks, setTasks] = useState(initTasks);
const deleteTask = (index) =>
{
let cp =tasks.filter(x=>x.id !== index);
setTasks(cp);
console.log(tasks);
};
const addTask =(text) =>
{
let newTask ={id:tasks.length+1,text:text};
setTasks([...tasks,newTask]);
}
return (
<Router>
<div className='container'>
<Header title='Titlee'/>
<AddTasks addTask={addTask}></AddTasks>
<Routes>
<Route path='/' element=
{
<>
{tasks.length > 0 ? (
<Tasks
tasks={tasks}
onDelete={deleteTask}
toggle={toggleReminder}
/>
) : (
'No Tasks To Show'
)
}
</>
}></Route>
<Route path='/about' element={<About />} ></Route>
</Routes>
<Footer></Footer>
</div>
</Router>
)
}
export default App;
My Tasks:
const Tasks =({tasks, onDelete, toggle}) => {
return (
tasks.map((task) => (
<Task key={task.id} task={task} onDelete={onDelete} toggle={toggle}/>
))
)
}
export default Tasks
and my Task.js
const Task = ({ task, onDelete,toggle }) => {
return (
<div className='task' onClick={()=>toggle(task.id)} key={task.id}>
<h3>{task.text}
<FaTimes
style={{color: 'red', cursor: 'pointer'}}
onClick={()=>onDelete(task.id)}/>
</h3>
<p>{task.id}</p>
</div>
)
}
export default Task
I have init state with 3 hardcoded tasks in App.js. Adding new tasks works proper, and tasks are succesfully updated. The problem is with deleteTask - in 'cp' collection I have updated list of tasks, but console.log (fired just after setTasks) is shows not updated collection. Why? What is improperly done, and how to explain this bug? Moreover - lists of my tasks are not updated (in html) - why? Regards
EDIT: It doesn't matter how I initialize array with tasks. Deleting doesn't work even on case with empty array at the begining
useState. Where and how exactly aretasksandsetTasksbeing initialized in your code? Could you update your question to provide it, because that’s the only reason I can think of as to why your DOM wouldn’t be updating properly.