harsh
harsh

Reputation: 114

Array is not getting updated by useState

function App() {

  let [task, setTask] = useState('');
  let [taskList, updateTaskList]= useState([]);

  let updateList = function (event) {
    event.preventDefault();
    console.log(task);
    updateTaskList([
      ...taskList,
      {text: task, id: Math.random()*1000}
    ]);
    console.log(taskList);  
  }


  return (
    <div className="App" >
      <div>
        <h3 className="heading">Task list</h3>
        <form onSubmit={updateList}>
          <input type="text" className="input-section"
            placeholder="Enter your tasks" value={task}
            onChange={(event) => { setTask(event.target.value) }} />
          <span className="fa fa-plus-square" aria-hidden="true"></span>
        </form>
         {/* {taskList.map((eachValue) => (
            <AddList listItem={eachValue} />
          ))};  */}
      </div>
    </div>
  );
}

Here is the piece of my code, I am trying to create a to-do list here. But the updateTaskList is not working properly. After we enter some value in the input box, and press enter the taskList is showing empty array. I don't understand what I am doing wrong, can someone please tell me what I am doing wrong

Upvotes: 0

Views: 50

Answers (1)

dumbape
dumbape

Reputation: 55

updateTaskList is asynchronous. It is probably updating your list, but you cannot see it because you immediately print the list after updateTaskList. Try adding a delay and then print task list or use useEffect to print it.

    setTimeout(() => console.log(taskList), 500)

OR

    useEffect(() => {
      console.log(taskList)
    }, [taskList.length])

Upvotes: 1

Related Questions