Home > Software engineering >  How can I have multiple states in the javascript array only when it's pressed?
How can I have multiple states in the javascript array only when it's pressed?

Time:02-16

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)
  }

CodePudding user response:

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.

CodePudding user response:

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 ))
}
  • Related