0

I am trying to build my 1st ToDo-list-app in React & I can't seem to successfully read the data from my "list" array which I've initiated using useState([]). The issue I'm facing is - if my 1st entered task is "1-Eat Breakfast" & I click on the add button, I'm getting an empty array in console.log, When I enter my 2nd task lets say - "2-Hit the gym"; that's when my previous task is getting console logged. So, apparently I am unable to read the latest state of my array - "list". Can you please point out what I am doing wrong in the code given below? Thanks a lot.

import { useState } from "react";

const ToDo = () => {
  const [task, setTask] = useState("");
  const [list, setList] = useState([]);

  const readData = (event) => {
    event.preventDefault();
    setTask(event.target.value);
  };

  const showList = (event) => {
    event.preventDefault();
    setList([...list, task]);
    console.log(list);
  };

  return (
    <div>
      <div>
        <form onSubmit={showList}>
          <input type="text" value={task} onChange={readData} />
          <button>Add to List</button>
        </form>
      </div>
    </div>
  );
};

export default ToDo;
Nikhil J
  • 3
  • 2
  • 2
    `console.log` won't print your latest version. See: https://stackoverflow.com/questions/31702861/when-value-is-assigned-to-components-state-why-console-log-prints-the-previous or this: https://stackoverflow.com/questions/54867616/console-log-the-state-after-using-usestate-doesnt-return-the-current-value – coglialoro Apr 20 '22 at 11:27

1 Answers1

0

can you change

 const showList = (event) => {
    event.preventDefault();
    setList([...list, task]);
    console.log(list);
  };

to

 const showList = (event) => {
    event.preventDefault();
    list.push(task);
    setList(list);
    console.log(list);
  };
Santosh Karanam
  • 1,077
  • 11
  • 23