I have a function, which dynamically changes objects on page with CSS animations.
I call this function from an onclick and touchend event.
I want to prevent this function from running/calling if animation is still in the process.
The strange thing is that in the code below function changeItem is called even if isLoading from console.log(isLoading) equals false.
const [isLoading, setIsLoading] = useState(false);
const changeItemHandler = (mod, index) => {
console.log(isLoading);
if (isLoading === true) return;
else {
setIsLoading(true);
changeItem(mod, index); //at the end of animation setIsLoading(false) is called
}
};
I have tried Julien Ripet answer, and ran into the same problems. Now with that code:
const [animAttrs, setAnimAttrs] = useState({isLoading: false, mod: null, index: null});
const changeItemHandler = (mod, index) => {
if (animAttrs.isLoading === true) return;
else setAnimAttrs({ isLoading: true, mod: mod, index: index });
};
useEffect(() => {
if (animAttrs.mod == null) return;
//needed to not call this function only after click or swipe
else changeItem(animAttrs.mod, animAttrs.index);
//onanimationend i call setAnimAttrs({isLoading:false,mod:null,index:null});
}, [animAttrs]);
It also calls changeItem function even if animAttrs.isLoading === true. I just can't explain this behavior.