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

Handle Select Option in React giving me empty string first time

I am very new to reactjs . I need handle the select option in my form . And set ne useStae correspond to select option and store the value of option on change event. But the problem is that when I select the first time any option then it gives me an empty string.

This is code

const [gender,setGender] = useState("")

 const genderHandle = (e) =>{
        setGender(e.target.value)
        console.log(gender)
    }
  <select onChange={genderHandle}> 
      <option selected disabled>What is your gender?</option>
      <option value="Male">Male</option>
      <option value="Female">Female</option>
      <option value="Unknown">Unknown</option>
      <option value="Anther Gender">Another Gender</option>
   </select> 


output ""

Am I doing something wrong ?

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 :

I assume you are referencing the output of your console.log.

The reason it is displaying the previous state is because the setState method is asynchronous, meaning your state has not been updated by the time your console.log is called.

theres many different ways this can be resolved, however the simplest may be moving the console.log outside of genderHandle

const [gender,setGender] = useState("");
console.log(gender);
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