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

useState asynchronous problem with select

i have a problem with my useState function when i use select, actually i get the previous value on the selected option instead of the selected option

  const [option, setOption] = useState('');

               <select
                className="form-select"
                aria-label="Default select example"
                onChange={(e: React.ChangeEvent<HTMLSelectElement>) => {
                  const newVal: string = e.target.value;
                  setOption(newVal);
                  console.log(option);
                }}
              >
                <option selected>selectionne ta couverture</option>
                <option value="Spot">Spot</option>
                <option value="Forward">Forward</option>
                <option value="Swap">Swap</option>
              </select>

how do i make it get the selected value

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 :

Setting the state in React acts like an async function.
Meaning that the when you set the state and put a console.log right after it, it will likely run before the state has actually finished updating.

Which is why we have useEffect, a built-in React hook that activates a callback when one of it’s dependencies have changed.

Example:

useEffect(() => {
   // Should show updated state -
   console.log(state);
}, [state])

The callback will run only after the state has finished changing and a render has occurred.

  • Note: "state" in the example is interchangeable with whatever state piece you’re dealing with, such as option in this case.

Check the documentation for more info.

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