Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

React State Shows False When True Is Expected

Very simple goal. When a checkbox is clicked set the state of itemOne to true initially. Then it should toggle state if clicked again. When itemOneSelected is invoked itemOne is shown as false.

The question: Why is itemOne set to false instead of true when itemOneSelected is invoked?

      const [itemOne, setItemOne] = useState(false);
      const itemOneSelected = () => {
      setItemOne(!itemOne)
      console.log(itemOne)
      }

    
      <FormControlLabel control={<Checkbox onClick => { itemOneSelected() } } />} 

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Remember useState is asynchronous so it will not update straight away. To get the console.log value to log your value you should add a useEffect.

    useEffect(() => {
        console.log(itemOne) 
    },[itemOne])
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading