I have 2 functions, onTouchStart and onTouchEnd, where onTouchEnd uses a state variable that onTouchStart sets. I'm worried that the onTouchEnd function could read the wrong value of a state variable because onTouchStart might not have finished setting the state. The main problem is that I don't want onTouchEnd to get triggered every time onTouchStart finishes, but need onTouchStart to set the state-stored variable to the correct value before onTouchEnd executes.
onTouchStart(){
this.setState({
randomBool: true
});
}
onTouchEnd(){
console.log("randomBool should be true: " this.state.randomBool);
//then some stuff here
}
CodePudding user response:
You can use a check followed by setTimeout:
onTouchEnd(){
if (!this.state.randomBool)
setTimeout(this.onTouchEnd, 10);
//then some stuff here
}
If needed you can also pass parameters into the "recursive" call: setTimeout(() => this.onTouchEnd(v1, v2), 10);
CodePudding user response:
In order to do this deterministically, you need some state to which you can write synchronously, and you need something to indicate that setState has completed.
(I'm making an assumption here that setState provides this indication in the form of a promise).
In the snippet below, hold the mouse down for less than a second, and then try again for more than a second...
document.getElementById("touchMe").addEventListener('mousedown', onTouchStart);
document.getElementById("touchMe").addEventListener('mouseup', onTouchEnd);
let state; // assuming we can only read and write this async...
// ...with this getter and setter
async function setState(object) {
return new Promise(resolve => {
setTimeout(() => {
state = object
resolve()
}, 1000);
})
}
async function getState() {
return new Promise(resolve => {
setTimeout(() => {
resolve(state)
}, 1000);
})
}
// BUT, we can write this synchronously
let settingState = false;
function onTouchStart() {
settingState = true;
setState({ someBool: true }).then(() => {
settingState = false;
})
}
function onTouchEnd() {
if (settingState) {
console.log("giving up, because we're busy writing state");
return;
}
console.log("we can get state now");
getState().then(state => console.log(state));
}
<div id="touchMe" style="background-color:yellow;">Touch Me</div>
