'How to set state using useState and do something else as well in onChange in React?

I have a component which includes another component (from headlessui/react) defined as follows:

export default function MyComponent(props) {
  const [selectedState, setState] = useState('');
  return (
    <div>
      <RadioGroup value={selectedState} onChange={setState}>
      ...
      </RadioGroup>
    </div>
  )
}

In the onChange I would like to first call a function which does something and then calls setState. However, nomatter what I try, I can't get this to work.

I've tried:

onChange={() => {
  doSomethingFirst();
  return setState;
}

onChange={() => {
  doSomethingFirst();
  // This requires an argument and I'm not sure what the argument should be
  setState();
}

// Even this fails
onChange={() => setState;}

What do I do to get this working?



Solution 1:[1]

This should works.

export default function MyComponent(props) {
  const [selectedState, setState] = useState('');

  const updateState = (ev)=> {
    doSomethingHere();
    ...
    setState()
  }
  
  return (
    <div>
      <RadioGroup value={selectedState} onChange={updateState}>
        ...
      </RadioGroup>
    </div>
  );
}

ev object passed to updateState function contains <RadioGroup> element. You can inspect it with console.log to see what values it holds.

If you are trying to update the state according to the RadioGroup value, you must be able to read that value inside ev object.

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 Robinson Ody