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