'How can I have multiple states in the javascript array only when it's pressed?
I made a to-do app that has Incompleted, Completed, and Deleted sections. Each Incompletedand Completed section has onClickDelete buttons, and when it's pressed, the task is supposed to be sent to the Deleted section.
However, it is sent to the Deleted section but it always contains an empty task. I know that my code is successfully pushing multiple states in the array but not sure how to fix it.
I tried
const newDeletedTodos = [...deleteTodos, incompeleteTodos[index],completeTodos[index]]
or
const newDeletedTodos = [...deleteTodos, incompeleteTodos[index]||completeTodos[index]] but didn't work.
I appreciate any advice!
const onClickDelete = (index) => {
//works fine
const newTodos = [...incompeleteTodos]
newTodos.splice(index, 1)
//works fine
const newCompletedTodos = [...completeTodos]
newCompletedTodos.splice(index, 1)
//Works strange.
const newDeletedTodos = [...deleteTodos]
newDeletedTodos.push(incompeleteTodos[index])
newDeletedTodos.push(completeTodos[index] )
setIncompleteTodos(newTodos)
setCompleteTodos(newCompletedTodos)
setDeleteTodos(newDeletedTodos)
}
Solution 1:[1]
as per @titus suggestion, you state can be like
const [todos, SetTodos] = useState<{ id: string;
text: string;
state: "uncomplete"| "complete"| "deleted" }>([])
const onClickDelete = (id) => {
SetTodos(prev => prev.map(x => x.id === id ? {...x, state: 'deleted'} : x ))
}
Solution 2:[2]
For React state updates that depend on the previous value, the callback argument must be used. This is due to the asynchronous nature of state updates (docs)
Eg. to remove an element.
var index = 5;
setTodos((todos)=>(
todos.filter((t,i)=> (
index != i
)
)
Similiary concat can be used to append to the array.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Himanshu Patil |
| Solution 2 | Nice Books |
