0

I am trying to put the user input into my array.

on the initial click of my button its logging out:

input Todo: wash car

Todo List Array:

Questions 1. Why is "todo List Array" not showing "Todo List Array: [ ]" as an empty array?

On the second click of my button its logging:

input Todo:

Todo List Array: wash car (because I typed in wash car in input)

I see that my array is updated on second click. Any reason why its taking two clicks to have my array updated?

my code is below:

 const [inputTodo, setInputTodo] = useState("")
    const [todoList, setTodoList] = useState([])
  
    function handleSubmit(){
        console.log(`input Todo: ${inputTodo}`)
        setTodoList(inputTodo)
        setInputTodo("")
        console.log(`Todo List Array: ${todoList}`
    }

    return(
        <div className="addTodo__container">
                    
                <div className="add-Todo__inputWrapper">
                  <input
                    className="add-Todo__input"
                    name="todo"
                    type="text"
                    placeholder="ADD TODO"
                    value={inputTodo}
                    onChange={(e) => setInputTodo([e.target.value])}
                    />
                </div>
             
           <div className="add-Todo__taskButtonContainer">  
            <button className="add-Todo__taskBtn" onClick={handleSubmit}>New Task</button>
            </div>
        </div>
skyboyer
  • 22,209
  • 7
  • 57
  • 64
meeshaa
  • 133
  • 9
  • 1
    Does this answer your question? [useState set method not reflecting change immediately](https://stackoverflow.com/questions/54069253/usestate-set-method-not-reflecting-change-immediately) – T J May 10 '21 at 19:06
  • 1
    T J, I appreciate it, after reading this article I was able to figure it out by implementing useEffect. – meeshaa May 10 '21 at 20:20

1 Answers1

0

The value of todoList is stale inside of the handleSubmit closure. See e.g. this article for details.

thisisrandy
  • 2,660
  • 2
  • 12
  • 25