'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



Solution 1:[1]

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.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1