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

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:

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

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 :

When you pass onChange directly to RadioGroup it will invoke your setState with any arguments the RadioGroup supplies. Because setState only takes one argument that’s thereby equal to doing onChange={arg => setState(arg)} which already shows how to accomplish what you’re trying to do. Just emulate this exact behaviour and add in your function call:

onChange={arg => {
  doSomethingHere()
  return setState(arg)
}}
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