dayhaysoos / use-shopping-cart

Shopping cart state and logic for Stripe
MIT License
907 stars 118 forks source link

ClearCart not clearing on success page in NextJS 13.4.9 app folder. #340

Open graemec23 opened 6 months ago

graemec23 commented 6 months ago

I have a weird bug, I cant get the Cart to clear on the success page after returning from stripe.

If I click on another page, then return to the success page the cart clears. Its just when I come to that page from stripe, or copy / paste the url into a browser. The clearCart function is wrapped in a useEffect like below, and is in a 'use client' component.

useEffect(() => { clearCart(); }, []);

I have found if I wrap the clearCart in a setTimeout it works, but this feels like bit of a hack. Has anyone else had this issue?

mrarvind90 commented 5 months ago

@graemec23 experiencing this issue too with NextJS 14. Glad am not the only one who tried the setTimeout hack 😅 . Did you manage to figure out what is happening?

graemec23 commented 5 months ago

@mrarvind90 not yet sorry, Ive not had a chance to look at it again.

levipadre commented 4 months ago

Has anyone solved this yet?

levipadre commented 4 months ago

Temp solution for me, because weirdly it's working with click.

const { clearCart, cartCount } = useShoppingCart();
const buttonRef = useRef<HTMLButtonElement>(null);

    useEffect(() => {
        if (typeof cartCount != 'undefined' && cartCount > 0) {
            const interval = setInterval(() => {
                if (buttonRef.current) {
                    buttonRef.current.click();
                }
            }, 100);

            return () => {
                clearInterval(interval);
            };
        }
    }, [cartCount]); 

and <button className='d-none' ref={buttonRef} onClick={() => clearCart()}>Clear cart</button>