Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

198
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda