4

I have a form which, when I submit, should call up 2 functions one by one and then run a condition that is dependent on the mentioned 2 functions.

The handler starts when you press the button, but how do you ensure that they will run sequentially and wait for the result of the previous one?

  const handlerNextPage = () => {
    controlValidInputs();
    handlerSetValues();

    inputsData.pages.isValid.page1 && navigate("step2");
  };

Thank you

2

3 Answers 3

3

if they are synchronous functions so you don't need to worry about they will run one by one but if you are setting state which is asynchronous or calling API in the function which I see that's not the case here. But if you still call an API here in the function you can handle in quite easily by making the function into an async function and putting await but if you setstate and use it value right that is the tricky part because setState need little bit time before setting it so you need to update your logic little bit suppose handlerSetValues(); you setState in this function like this:

const handlerSetValues = () => {
 // code here
 // code here
 // get value of state
 setState(value) // this take little bit time so
 return value // as well and use it handlerNextPage function
}
  const handlerNextPage = () => {
    controlValidInputs();
    const value = handlerSetValues();
    // now use value as state like you use below code I think.
    inputsData.pages.isValid.page1 && navigate("step2");
  };
Sign up to request clarification or add additional context in comments.

Comments

2

It depends from the nature of your functions and what you are doing inside of them. If they execute all synchronous tasks, they will be called sequentially and will execute sequentially one after another, that's due to the synchronous single threaded nature of JavaScript engine Event Loop.

BUT

If inside one of those functions you are performing some asynchronous task, like an http fetch or a setTimout, the next function will be executed while the previous one async operations have not been performed yet. To handle those cases you need to use promises.

In your case I don't think you have any asynchronous task in your first function controlValidInputs() and in the second one I assume you are performing some React setState, the React setState is asynchronous but can't be handled with promises, you need to use the useEffect hook to defer operations after a react state update.

Comments

0

you can useeffect

useEffect(()=>{

// inputsData.pages.isValid.page1 && navigate("step2");

},[depency-OnChanging-Which-Call-Code-Inside-Effect])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.