0

How can i set the state of a variable using setState and then use same variable inside a function that gets called into a click event?

function example(){
const [state,setState]=useState()

 async function getData(){
  try{
   --some code--
   const example1={field: state};
   };
  catch(){}
}
 return <button 
  onClick{()=>{
   setState();
   getData();
 }}>
  </button>
}

As you can see i am trying to use setState and also a function that contains the state variable inside the same onClick event. Problem is, i have to click twice for it to work. Basically first click does setState and second click runs the function. How can i execute both setState and getData inside the same onClick event?

Mark t
  • 85
  • 5
  • State updates are batched/asynchronous and not immediately available. You can respond to the state update itself with `useEffect`, or you could pass the new value directly to `getData` as a function parameter. – David Mar 17 '22 at 13:53

0 Answers0