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

Time:02-08

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?

CodePudding user response:

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)
}}

CodePudding user response:

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.

  •  Tags:  
  • Related