I'm coding a simple todo app using hooks, Its functions are(add task, remove task, edit task)... basic stuff
Everything seems to work okay except for the delete button. when I click delete on any element, the last element gets deleted everytime.
the functions for the operations :
const [task,setInput] = useState() #new todo
const [todolist,setList] = useState([]) #the todos
const [edit, setEdit] = useState(false) #editing
# I am able to control the text input through this
function handleInput(e){
e.preventDefault()
setInput(e.target.value)
console.log(e.target.value)
}
function handleSubmit(e){
e.preventDefault()
setList([...todolist,{text:task,id:uuidv4()}]) # each todo has a unique id
setInput("")
}
function remove(id){
setList(todolist.filter(t =>t.id !== id)) # Here is the potential issue
}
I am passing all the states and functions to the children components
I have a todoList componant that map each task to a Task component the mapping works correctly,
the Task component has an onClick function like this:
function handleRemove(){
remove(props.task.id)
}
On theory the remove handler should remove the task with the specific id, yet it removes another task.
current investigations:
when clicking handleRemove the correct id passes, todolist state has the correct updated list
I'm gonna start this mini project from scratch, yet it would be helpful if I understood why this happened.
Example:
- This is the first Task x
- This is the second Task x
- This is the third Task x
state = [{text:'This is the first Task,id:1},
{text:This is the second Task,id:2},
{text:This is the third Task,id:3}]
-------------------------------------------------------------------------------
clicking on X belonging to first task will yield
- This is the first Task x
- This is the second Task x
state = [{text:This is the second Task,id:2},
{text:This is the third Task,id:3}]
---------------------------------------
deleting the first task again will yield
- This is the first Task x
state = [{text:This is the third Task,id:3}]