Running Functions One After Other in React

running functions one after other in react

this.setState does not return "Promise" and that's why it is not proper to use "then" method to chain the operations. ref.

If your "service.logout(..)" returns Promise than probably following one will work.

componentWillMount() {
if (!(this.Auth.loggedIn())){
this.props.history.replace('/login');
} else {
const authToken = this.Auth.getToken();
this.setState({token : authToken }, () => {
service.logout(authToken).then( this.Auth.logout());
});
}

}

React: How to force a function to run after another one is totally completed?

The solution:

Use an array to hold states and duration:

const states = [ { name: 'session', duration: 1500 }, { name: 'break', duration: 300 } ]

Alternate the index of the array to alternate between session and break.

countDown(id){
// set the function to a variable and set state to it, so the function
// can be paused with clearInterval()
var intervalFunc = setInterval(() => down(this.state.timeLeftSeconds--), 1000);
this.setState({intervalFunc: intervalFunc});

const down = (time) =>
{

if(time > 0){
// converts seconds to MM:SS at every t-minus
this.setState({ timeLeft: secondsToMins(time)});
console.log(time);
console.log(this.state.timeLeft);
}

if (time <= 0) {
this.setState({ timeLeft: secondsToMins(time)});
let sound = document.getElementById(id).childNodes[0];
sound.play();

let stateIndex = (this.state.stateIndex + 1) % states.length;
this.setState({ stateIndex: stateIndex});
this.setState({ timeLeftSeconds: states[stateIndex].duration});
this.setState({ init: states[stateIndex].name});
console.log(this.state.init);
}
}
}

How to run functions one after the other after one function has fully executed when functions are both synchronous and asynchronous

Since getValue is an async function, it returns a Promise object, and you want other functions to be executed after getValue has completed it's execution, you can either use .then() or await on getValue.

Using .then().

 submit = () => {

this.props.getValue().then(res=>{
this.props.toggle(); //All these functions execute only after getValue has completed it's execution.
this.notify();
this.props.resetValidation();
this.props.disable();
this.props.actionCost();
})
};

Using await

submit = async() => {
await this.props.getValue(); //Note that this should be placed on top as this is the function you want to run first, and other functions to execute only after this has completed.
this.props.toggle();
this.notify();
this.props.resetValidation();
this.props.disable();
this.props.actionCost();
};

Since your getValues function uses an axios function, you should return the promise after axios has completed its operation. Your getValues should be something like this:
Making getValues an async function

const getValues = async() =>{
let res = await axios.get('URL') //Just an instance, change the axios method(GET,POST,PUT) according to your needs.

return res
}

(OR)
Return a promise from getValues.

const getValues = () =>{
return new Promise((resolve,reject)=>{
axios.get('URL',response=>{
resolve("AXIOS REQUEST COMPLETE")
}
})
}

You can update your getValues to any of the above-described ways, and call getValues as shown earlier and it shall work as expected.

How to make axios call one after the other in React

you can use async await for that, or move your second request into then({...})

please read async await reference

this one example using async await

onHandleDeactivate = async () => {
let payLoad = {
Id: this.state.Id,
}
try {

// first call
let response = await axios.post('/deactivate', payLoad)
this.closeDeactivateModal()
this.setState({ successMessage: `Deactivated successfully.` })

// second call
try {
let result = await axios.get('/get')
this.setState({ result: result })
} catch (error) {
this.setState({ message: error.message })
}

} catch (error) {
this.setState({ errorMessage: error.message })
}
}


Related Topics



Leave a reply



Submit