Search code examples
reactjsreact-hooksuse-state

How to read the value of updated array while using useState hook in react?


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;

Solution

  • 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);
      };