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

123
Vistas
Preact clear array in functional component does not remove all output

I am very new to frontend development and trying to build a simple todo compoment. I have a problem to reset the array. Always one item remains in DOM. But only the "DEL"-button.

All other functions / hooks work as expected.

This is the code:

import { useState } from 'preact/hooks';

const Todo = () => {
  const [input, setInput] = useState('')
  const [todos, setTodos] = useState([])

  const onInput = ev => {
    setInput(ev.target.value)
  }

  const deleteItem = itm => {
    setTodos(todos.filter(el => el != itm))
  }

  const deleteList = () => {
    setTodos([])
  }

  const onSubmit = ev => {
    ev.preventDefault()

    // const out = todos.push(input)
    setTodos([...todos, input])
    setInput('')
  }

  return (
    <>
      <form onSubmit={onSubmit}>
        <input
          type="text"
          onInput={onInput}
          value={input}
          placeholder="Todo..."
          autoFocus="autofocus"
        />
        <button type="submit">Eingabe</button>
        <button onClick={deleteList}>CLEAR</button>
      </form>
      <ul>
        { todos.map(el => {
          return (
              <li>
                {el}
                <button onClick={() => deleteItem(el)}>DEL</button>
              </li>
          )
        }) }
      </ul>
    </>
  )
}


export default Todo
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Your submit function will add input to your todo list, even if input is is an empty string. This is why you have a single DEL button in your list. Instead, check if input is empty, and if is, then return.

  const onSubmit = ev => {
    ev.preventDefault();
    if(input === '') {
      return;
    }

    // const out = todos.push(input)
    setTodos([...todos, input])
    setInput('')
  } 
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