Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

122
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda