I was playing around coding a simple e-commerce food app in React, and I wanted the cart button to 'wobble' every time an item was added to the cart (the food items are in a different component hence useContext).
useEffect(() => {
if (cart.state.totalItems > 0) {
setWobble(true);
}
const timer = setTimeout(() => {
setWobble(false);
}, 300);
return () => {
clearTimeout(timer);
};
}, [cart.state.totalItems]);
The problem I ran into with the code above was if an item was added before the timer (which runs for the length of the animation) runs out (quick clicks, for example), the timer would be cleared and the animation would 'freeze' until the last click when it would complete the timer. To change this I added a key to the cart button (which is equal to the total items in cart, so it's always changing) so that each time a new item is added, the key is changed, and, therefore, a new button is rendered, and thusly, the animation restarts.
What I've realised since starting to learn to code is, more often than not, I tend to hack my way to functionality, and I was wondering if there was a more standard way of doing this?
I'm also currently learning styled-components hence the element names.
const Header = props => {
const cart = useContext(InCartContext);
const [wobble, setWobble] = useState(false);
useEffect(() => {
if (cart.state.totalItems > 0) {
setWobble(true);
}
}, [cart.state.totalItems]);
const setModal = () => {
props.modalOpen(true);
};
return (
<HeaderStyles>
<HeaderTitle>Food App</HeaderTitle>
<CartBtn
btnSize="large"
display="flex"
onClick={setModal}
wobble={wobble}
key={cart.state.totalItems}
>
<CartIconStyled />
Cart
<CartNumberDiv>
<CartNumber>{cart.state.totalItems}</CartNumber>
</CartNumberDiv>
</CartBtn>
</HeaderStyles>
);
};
export default Header;