Home > Software engineering >  How to stop a function in react
How to stop a function in react

Time:11-23

It seems that getresult() is trying to console.log('here', x) before getMathvalue() finish is task. I would like to "pause" getresult() so it would only console.log('here', x) when getMathvalue() is done

Here I'm trying to get a specific value a only this value which is value after getMathvalue() finished is task

function quickmath() {

  const [value, setvalue] = useState()

  function getMathvalue() {
    var a = 1
    a  
    setvalue(a)
  }

  useEffect(() => {
    getMathvalue()
  }, [])

  getresult({ value })

  function getresult(x) {
    console.log('here', x)
  }

Obtained Output:

Expected Output:

Edit ---

I added and ,

  useEffect(() => {
    getresult({ value })
  }, [value]);

there is still value as undefined

CodePudding user response:

You need to wrap the function call in useEffect, then everything will work correctly:

  useEffect(() => {
    getresult({ value })
  }, [value]);
  

  function getresult(x) {
    console.log('here', x)
  }

The functional components of react work like normal functions. Any change in the state of the component causes the entire code inside the function (component) to be called.

To respond to changes in the values in the state, use useState with the necessary dependencies.

CodePudding user response:

What is happening is that on the first render, you are calling the getresult function and also triggering the useEffect call. That is why the value starts as undefined.

If you want to get the specific value as soon you change the state you can wrap your method in other useEffect call:

useEffect(() => {
  // using an if clause because *value* starts as undefined on the first call
  if (value) {
    getresult({ value }); // this method would be called each time the *value* changes
  }
}, [value]);

With this, you would be able to avoid calling the getresult method on each render (don't forget to remove it from your main component).

CodePudding user response:

There are few cases for this situation, if you are talking about output from first render, then this code works fine, because useEffect will call it's function only after first render will finish, so your getresult() will be called earlier then getMathValue().

Its hard to understand what real life situation you are trying to solve here because code is abstract.

For example if you want to make something after your value will be updated, you can create a second useEffect with value in dependency array. That way you will get your getresult function called after your getMathValue will finish its work.

useEffect(() => {
  getresult({value}) // will be called after value was updated
}, [value])

If this explanation\solution doesn't help you, pls, provide more case specific details to better understand situation.

Hope it helped.

  • Related