navigating away from a page.
Unanswered
Brown bear posted this in #help-forum
Brown bearOP
"use client";
import { Elements } from '@stripe/react-stripe-js';
import { loadStripe } from '@stripe/stripe-js';
import { useSearchParams } from 'next/navigation';
import { useEffect, useState } from 'react';
export default function CheckoutPage() {
const searchParams = useSearchParams();
const [pending, setPending] = useState(true);
const booking_id = searchParams.get('booking_id');
useEffect(() => {
if (!pending) return;
function beforeUnload(e) {
e.preventDefault();
// Using navigator.sendBeacon instead of fetch for beforeunload event
const data = JSON.stringify({ booking_id: booking_id });
navigator.sendBeacon('/api/delete-hold', data);
// Optionally, you can show a confirmation dialog
const message = "Are you sure you want to leave?";
e.returnValue = message;
return message;
}
window.addEventListener('beforeunload', beforeUnload);
return () => {
window.removeEventListener('beforeunload', beforeUnload);
};
}, [pending, booking_id]);
// char limit
return ()
}i am having problems sending a api request to delete a hold if the page exits without payment confirmation. I have not passed in the pending to checkout form (just for debugging). can you give me advice/point to towarda a solution i am using Next.js 14+
I just want the page to send a api request before navigating away. That's it.
1 Reply
Brown bearOP
i updated it, the last line is basically my question.