Home  >  Q&A  >  body text

Analysis: Why does an empty element appear at the first index position every time?

<p>Whenever I try to put something into my to-do list, there is always an empty element at the first index. Why does this happen? </p> <pre class="brush:php;toolbar:false;">const [todoList, setTodoList] = useState([]); const addToList = (inputText) => { if (inputText === "") { alert("The list is empty") }else{ setTodoList([inputText, ...todoList]) } console.log(todoList); }; const addList = (inputText) => { addToList(inputText); };</pre> <pre class="brush:php;toolbar:false;">const [todoList, setTodoList] = useState([]); const addToList = (inputText) => { if (inputText === "") { alert("The list is empty") }else{ setTodoList([...todoList, inputText]) } console.log(todoList); }; const addList = (inputText) => { addToList(inputText); };</pre> <p>I also tried it but it didn’t work</p>
P粉878510551P粉878510551452 days ago380

reply all(1)I'll reply

  • P粉391955763

    P粉3919557632023-08-17 15:45:16

    Your

    setTodoList([inputText, ...todoList])
    

    Use a closure to get the todoList, so you get the same todoList every time.

    You need to do something like this:

    setTodoList(todoList => [inputText, ...todoList])
    

    reply
    0
  • Cancelreply