1

I want to show the option selected by the user in console in Select tag but as user select test1 console show me undefined and when user select test 2 then it show me previous selected value that is test1 and so on.

Component.jsx

<Form.Group controlId="exampleForm.ControlSelect1">

  <Form.Label>Login as</Form.Label>
  <Form.Control as="select" defaultValue="test1" onChange={getOptionValue} >
  
    <option>test1</option>
    <option>test2</option>
    <option>test3</option>
    
  </Form.Control>
</Form.Group>

useState

const [getOption, setOption] = useState();
    const getOptionValue = (e) => {
        setOption(e.target.value);
        console.log(`here is selected option${getOption}`);
    }
0

1 Answer 1

1

That's because the setOption will only take effect once the current function scope has ended and control has been given back to the react runtime. You

Here is a workaround if you really want to see the change right there:

const getOptionValue = (e) => {
   setOption(e.target.value);
   setTimeout(() => console.log(`here is selected option${getOption}`), 1);
}

The better solution would be to add that console.log statement right before the return statement of your render function (or functional react component).

Sign up to request clarification or add additional context in comments.

2 Comments

I got it, there is no need to use useState here so e.target.value or e.value worked for me. Thanks.
Glad it helped. Please don't forget to upvote and/or accept the answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.