vendredi 3 novembre 2023

Altering checkbox state in react js

This is my code for check box in react. Its from Material-UI

  const [checkmark, setCheckMark] = useState(false);

  const [selectedRows, setSelectedRows] = useState([]);

  const toggleAllCheck = (event) => {
    console.log("before", checkmark);
    setCheckMark(!checkmark);
    console.log("after", checkmark);
    let newSelectedRows;
    if (checkmark) {
      newSelectedRows = salesRows.map((row) => row.id);
      setSelectedRows(newSelectedRows);
      console.log("selected rows", newSelectedRows);
    }
  };

As checkmark state is initially set to false, there is no check-mark in the checkbox.

After I click the component, it shows a checkmark. The toggle is because of the toggleAllCheck function.

Inside the function, first it console logs the value of checkmark as false, which is understandable. On second line it alters the value to true. Which in turn gives a check-mark in my checkbox.

Then on third line, I again console log the value for checkmark. But it gives the false reading.

So, what I am confused about is why is it still false. I have the idea, that the state update happens in next render (been troubling me in other areas as well), but then how did I get the check on my check-box without any re-render.

Also, the same checkmark values is able to get me a check on the box, although its console log shows false, but is unable to execute the if statement.

I am trying to get a hold to selectedRows, when there is tick on checkbox, but I get that only in second click when the tick is removed.




Aucun commentaire:

Enregistrer un commentaire