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

125
Views
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 answers
Answer question

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 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!