0

My issue is that my useState is getting wrong numbers

when I print e.target.value it for example outprints 1 but my selectedIndex gives me 2 or when I get 0 selectedIndex retrives 1 stuff like that. Any ideas why this could happen ?

<Select
 id="SelectGrade"
  value={selectedIndex}
  //Important part
                      
   onChange={(e) => {
    console.log(e.target.value);
     setSelectedIndex(e.target.value),
     console.log(selectedIndex);

}}
>
 {pflegeengel.map(({ Vorname }, index) => {
        return (
          <MenuItem value={index} key={index}>
              {Vorname}
           </MenuItem>
          );
       })}
</Select>
Lucas Goldner
  • 617
  • 9
  • 29
  • setState is an async function. Refer to this: https://stackoverflow.com/questions/36085726/why-is-setstate-in-reactjs-async-instead-of-sync – Vivere Jan 10 '21 at 17:27
  • 1
    @Vivere no, `setState` is not an async function. State updates may be batched so the state may not be immediately changed after the `setState` call. A setter is a plain function and it doesn't generate a promise - everything is happening on the same call stack. It just happens that when React has control over user defined code, for example on a click event that is managed by React, it's React that calls all the user defined click handlers so it knows when all of them are done and can do all state updates at once at the end instead of triggering state change and render after each setter call. – marzelin Jan 10 '21 at 18:11

1 Answers1

3

When you console the state value imediately after setting will give you the older value. Is that your issue? Anyway the state will get updated. If you want to check the value change use as below after setting

React.useEffect(() => { console.log(selectedIndex)}, [selectedIndex]);
buzatto
  • 9,704
  • 5
  • 24
  • 33