Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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('')
  } 
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading