0

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 ?

Abhishek Poddar
  • 101
  • 1
  • 3
  • 8
  • You can't log right after setting state – pilchard Aug 29 '22 at 20:24
  • Does this answer your question? [The useState set method is not reflecting a change immediately](https://stackoverflow.com/questions/54069253/the-usestate-set-method-is-not-reflecting-a-change-immediately) – pilchard Aug 29 '22 at 20:25

3 Answers3

1

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.

HappyDev
  • 380
  • 1
  • 9
0

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])
dr0nda
  • 103
  • 6
0

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