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
Calculate Total Sum of Dynamically Added Items to a Table
Npm Warn Enoent Enoent: No Such File or Directory, Open 'C:\Users\Nuwanst\Package.Json'
Reprompt for Permissions With Getusermedia() After Initial Denial
Jquery Wait Until Ajax Call Has Got Data Before Displaying
How to Instantiate a JavaScript Class in Another Js File
How to Create a Remember Me Function in Login Without Using Form in JavaScript or Jquery
How to Split Date and Time from the Datetime Variable in JavaScript
Convert Date String from Yyyymmdd to Dd Mon Yyyy
How to Simulate Mouse Click Along With Mouse Move Using JavaScript
Increase JavaScript Heap Size in Create-React-App Project
Sort Json Data Based on Date and Time
How to Select Every 2Nd Element of an Array in a for Loop
Show Multiple Divs on Button Click
React Router Dom Returns a Blank Page When Going to a Particular Route
How to Parse Xml File in React