82 lines
2.2 KiB
JavaScript
Raw Normal View History

2024-08-25 18:15:45 -05:00
import { useState, useEffect, useCallback } from 'react';
2024-08-13 14:42:36 -05:00
import { useNDKContext } from "@/context/NDKContext";
2024-08-25 18:15:45 -05:00
import NDK, { NDKEvent, NDKSubscriptionCacheUsage } from "@nostr-dev-kit/ndk";
2024-08-25 18:15:45 -05:00
export function useZapsSubscription({ event }) {
2024-08-13 14:42:36 -05:00
const [zaps, setZaps] = useState([]);
const [zapsLoading, setZapsLoading] = useState(true);
const [zapsError, setZapsError] = useState(null);
2024-08-25 18:15:45 -05:00
const { ndk } = useNDKContext();
const addZap = useCallback((zapEvent) => {
setZaps((prevZaps) => {
if (prevZaps.some(zap => zap.id === zapEvent.id)) return prevZaps;
return [...prevZaps, zapEvent];
});
}, []);
2024-08-13 14:42:36 -05:00
useEffect(() => {
let subscription;
2024-08-25 18:15:45 -05:00
const zapIds = new Set();
let timeoutId;
2024-08-13 14:42:36 -05:00
async function subscribeToZaps() {
2024-08-25 18:15:45 -05:00
if (!event || !ndk) return;
2024-08-13 14:42:36 -05:00
try {
const filters = [
{ kinds: [9735], "#e": [event.id] },
2024-08-25 18:15:45 -05:00
{ kinds: [9735], "#a": [`${event.kind}:${event.pubkey}:${event.id}`] }
2024-08-13 14:42:36 -05:00
];
2024-08-04 19:00:26 -05:00
2024-08-25 18:15:45 -05:00
subscription = ndk.subscribe(filters, {
closeOnEose: false,
cacheUsage: NDKSubscriptionCacheUsage.CACHE_FIRST
});
subscription.on('event', (zapEvent) => {
2024-08-13 14:42:36 -05:00
if (!zapIds.has(zapEvent.id)) {
zapIds.add(zapEvent.id);
2024-08-25 18:15:45 -05:00
addZap(zapEvent);
setZapsLoading(false);
clearTimeout(timeoutId);
2024-08-13 14:42:36 -05:00
}
});
2024-08-04 19:00:26 -05:00
subscription.on('close', () => {
setZapsLoading(false);
})
2024-08-13 14:42:36 -05:00
subscription.on('eose', () => {
2024-08-25 18:15:45 -05:00
setZapsLoading(false);
2024-08-13 14:42:36 -05:00
});
2024-08-13 14:42:36 -05:00
await subscription.start();
// Set a 4-second timeout to stop loading state if no zaps are received
timeoutId = setTimeout(() => {
setZapsLoading(false);
2024-10-12 14:03:07 -05:00
}, 3000);
2024-08-13 14:42:36 -05:00
} catch (error) {
console.error("Error subscribing to zaps:", error);
setZapsError(error.message);
setZapsLoading(false);
}
}
2024-08-25 18:15:45 -05:00
setZaps([]);
setZapsLoading(true);
setZapsError(null);
subscribeToZaps();
2024-08-13 14:42:36 -05:00
return () => {
if (subscription) {
subscription.stop();
}
clearTimeout(timeoutId);
2024-08-13 14:42:36 -05:00
};
2024-08-25 18:15:45 -05:00
}, [event, ndk, addZap]);
2024-08-13 14:42:36 -05:00
return { zaps, zapsLoading, zapsError };
}