Home > Software design >  Handle Select Option in React giving me empty string first time
Handle Select Option in React giving me empty string first time

Time:08-30

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 ?

CodePudding user response:

Quoting the react docs:

Calling the set function does not change state in the running code
... states behaves like a snapshot. Updating state requests another render with the new state value, but does not affect the count JavaScript variable in your already-running event handler.

CodePudding user response:

The state will be set correctly, the only issue is the logging part. useState() is asynchronous so console.log() will be triggered before it even sets the new state. That's why you will always see the previous state.

You can see the real current state with something like this:

useEffect(()=>{
   console.log(gender)
}, [gender])
  • Related