0

functional component - react js I am running a process . I want to stop that process if user click on stop (stop button is on a diffrent component - Modal )

process function on app.js looks like

 const [terminate, setterminate] = useState(false);

const process =()=>{

... some code (has no use of terminate or setterminate)
for(let i=0;i<5;i++){

     if(terminate){
         break
        }

      // api call
    }
} // process function ends

const stopProcess = ()=>{
       setterminate(true)
}

// called a modal and passes stopProcess as prop. and when click stop button in modal, that invoke stopProcess function. but for loop insite process function dont get break

Modal.js

...

<button onClick={stopProcess}></ button >
...

everything works fine, except for does not breaks. function is invoked , tested by console.log("sdf")

how do I break that foor loop ?

skyboyer
  • 22,209
  • 7
  • 57
  • 64
  • 1
    It's not clear what you're asking, but I suspect the root cause is that you don't know state changes are asynchronous. Your terminate variable won't change until the next render. See [this question](https://stackoverflow.com/questions/54069253/the-usestate-set-method-is-not-reflecting-a-change-immediately) for more information on that. – samuei May 25 '22 at 16:49
  • from what I understood is you are asking how to pass the state to the modal component. You will have to pass that as a prop. Let me if I understood that right. Ill give you an answer. – joekevinrayan96 May 25 '22 at 18:08

1 Answers1

0

(clousers and working of useState (async ) and how it is update. (please read that first)) to get immediately value of useState

let temp_terminate=false;
  setterminateProcess((state)=>{
        temp_terminate=state;
        return state;
      })