Home > front end >  is there a way to wait till a function runs before an axis patch call
is there a way to wait till a function runs before an axis patch call

Time:04-30

I have a variable originalVar then I have another called updatedVar, when the user clicks a button originalVar needs to call a function - this function needs to set OriginalVar to updatedVar and then use axios patch to write it to db.

Do I need to use async or how would I do this to ensure this all updates because I need the originalVar to be updated to be used in another place ?

Sample code snippet:

const [saveButton,setSaveButton]= useState(false)
 
useEffect(()=>{
   if(saveButton)
      {
       setOriginalVar(UpdatedVar)
       //wait till this above statement runs then
       duplicateVar = originalVar
      }
    
}),[saveButton]

const finishButtonClick =() =>{
//do some logic 
setSaveButton(true) 
//wait till that finishes running and then,
axis.patch(blahblah,duplicateVar)
}

CodePudding user response:

const finishButtonClick = async () =>{
    //do some logic 
    setSaveButton(true) 
    //wait till that finishes running and then,
    const data = await axis.patch(blahblah,holdVar)
    //This will wait for the above line to finish
}

CodePudding user response:

   setOriginalVar(UpdatedVar)
   //wait till this above statement runs then
   duplicateVar = originalVar

What does setOriginalVar return? If it is a promise, you can do

   var p = setOriginalVar(UpdatedVar);
   //wait till this above statement runs then
   p.then(function(value) {
     duplicateVar = originalVar;
   });
  • Related