samedi 30 septembre 2023

Why is my setState in useState working the opposite way?

I am implementing a select all checkbox in typescript.

This is what it looks like: enter image description here The checkbox besides "Songs" is the select all checkbox,but when it turns to checked, the other checkboxed become unchecked,and become checked when it is unchecked,just like the picture shows.

It works fine in the first few change, but failed after about three change.

Here is my code:

const [check, setCheck]=useState(false);
async function allCheck(e:any){
  console.log(e.target.checked);
  setCheck(e.target.checked);
  console.log(check);
  e.stopPropagation();
  cards.forEach(async (card) =>{
    console.log(card);
    await updateCard(card.id, {
      checked : check,
    });
    let song=document.getElementById(card.id);
    console.log(song);
    if(song){
      let checkbox=song.querySelector('input[type="checkbox"]') as HTMLInputElement;
      if(checkbox){
        checkbox.checked = card.checked;
      }
    }
  });
  fetchCards();
}

Here is what the javascript console prints when the top checkbox is checked: enter image description here true is for console.log(e.target.checked) and false is for console.log(check)

Why is this happening?And I also want to know how to fix it. Thanks!




Aucun commentaire:

Enregistrer un commentaire