Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

200
Views
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)
  }
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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 ))
}
about 4 years ago · Juan Pablo Isaza Report

0

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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!