Adding new object to array of objects using useState is not working in React

Viewed 30

I am trying to add new object to array of objects but I can see in console it's not updating the users array. Can you please help me to understand what's wrong with this code.

function Details() {
  const [user, setUser] = useState({
    prn: 1,
    name: "",
    gender: "M",
    mobile: 1234567890,
    dept: "",
    year: "",
    sem: ""
  })

  const [users, setUsers] = useState([
    {
      prn: 12,
      name: "Shrut",
      gender: "M",
      mobile: 1234567890,
      dept: "CSE",
      year: "First",
      sem: "Second"
    },
    {
      prn: 13,
      name: "Shrutika",
      gender: "F",
      mobile: 1234567890,
      dept: "CSE",
      year: "First",
      sem: "Second"
    }
  ]);

  const onEnroll = () => {
    alert("Created successfully " + user.name + " " + user.dept);
    user.prn = 14;
    setUsers(oldList => [...oldList, user]);
    console.log(users);
  }
}
1 Answers

Your state is getting updated correctly. But the call setUsers(...) is asynchronous. You cannot expect to log the updated value right after it. But if you move the log to the component body level, then it will get logged in the next re-render.

  const onEnroll = () => {
    alert("Created successfully " + user.name + " " + user.dept);
    user.prn = 14;
    setUsers(oldList => [...oldList, user]);
    
  }
   
  console.log(users);
Related