Skip to content

Commit

Permalink
chore: testing sse
Browse files Browse the repository at this point in the history
  • Loading branch information
omelchenkoy committed Feb 20, 2025
1 parent 94d25ec commit 7d088ab
Showing 1 changed file with 42 additions and 23 deletions.
65 changes: 42 additions & 23 deletions src/pages/HomePage/Components/PaymentStatus.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,38 +9,57 @@ function PaymentStatus({ paymentHash, onSuccess }) {
useEffect(() => {
if (!paymentHash) return;

const eventSource = new EventSource(
`${API_ENDPOINT}/sse/subscribe?payment_hash=${paymentHash}`
);
let eventSource;

eventSource.onmessage = (event) => {
const message = JSON.parse(event.data)?.status;
const subscribeToEvent = () => {
eventSource = new EventSource(
`${API_ENDPOINT}/sse/subscribe?payment_hash=${paymentHash}`
);

// Handle special "end" message from server
if (message === 'paid') {
eventSource.close();
toast.success('Payment completed!');
setStatus('Payment completed!');
setIsPaid(true);
onSuccess();
return;
}
eventSource.onmessage = (event) => {
const message = JSON.parse(event.data)?.status;

// Handle special "end" message from server
if (message === 'paid') {
eventSource.close();
toast.success('Payment completed!');
setStatus('Payment completed!');
setIsPaid(true);
onSuccess();
return;
}

// Update status with server message
setStatus(message);
// Update status with server message
setStatus(message);
};

eventSource.onerror = (err) => {
console.error('EventSource error:', err);
toast.error('Something went Wrong');
eventSource.close();
setStatus('Connection error - please refresh');
};
};

eventSource.onerror = (err) => {
console.error('EventSource error:', err);
toast.error('Something went Wrong');
eventSource.close();
setStatus('Connection error - please refresh');
subscribeToEvent();

const handleVisibilityChange = () => {
if (document.visibilityState === 'visible' && !isPaid) {
subscribeToEvent();
} else if (eventSource) {
eventSource.close();
}
};

document.addEventListener('visibilitychange', handleVisibilityChange);

return () => {
eventSource.close();
if (eventSource) {
eventSource.close();
}
document.removeEventListener('visibilitychange', handleVisibilityChange);
};
}, [paymentHash, onSuccess]);
}, [paymentHash, onSuccess, isPaid]);

return (
<div>
Expand Down

0 comments on commit 7d088ab

Please sign in to comment.