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) =>{
  <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>

output ""

Am I doing something wrong ?

>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("");

Leave a Reply