plebdevs/src/hooks/nostrQueries/zaps/useZapsSubscription.js

68 lines
1.9 KiB
JavaScript
Raw Normal View History

import { useState, useEffect } from 'react';
2024-08-13 14:42:36 -05:00
import { useNDKContext } from "@/context/NDKContext";
2024-08-13 14:42:36 -05:00
export function useZapsSubscription({event}) {
const [zaps, setZaps] = useState([]);
const [zapsLoading, setZapsLoading] = useState(true);
const [zapsError, setZapsError] = useState(null);
const ndk = useNDKContext();
2024-08-13 14:42:36 -05:00
useEffect(() => {
let subscription;
let isFirstZap = true;
const zapIds = new Set(); // To keep track of zap IDs we've already seen
2024-08-13 14:42:36 -05:00
async function subscribeToZaps() {
try {
const filters = [
{ kinds: [9735], "#e": [event.id] },
{ kinds: [9735], "#a": [`${event.kind}:${event.id}:${event.d}`] }
];
await ndk.connect();
console.log("filters", filters);
subscription = ndk.subscribe(filters);
2024-08-04 19:00:26 -05:00
2024-08-13 14:42:36 -05:00
subscription.on('event', (zapEvent) => {
console.log("event", zapEvent);
// Check if we've already seen this zap
if (!zapIds.has(zapEvent.id)) {
zapIds.add(zapEvent.id);
setZaps((prevZaps) => [...prevZaps, zapEvent]);
2024-08-04 19:00:26 -05:00
2024-08-13 14:42:36 -05:00
if (isFirstZap) {
setZapsLoading(false);
isFirstZap = false;
}
}
});
2024-08-04 19:00:26 -05:00
2024-08-13 14:42:36 -05:00
subscription.on('eose', () => {
console.log("eose");
// Only set loading to false if no zaps have been received yet
if (isFirstZap) {
setZapsLoading(false);
}
});
2024-08-13 14:42:36 -05:00
await subscription.start();
} catch (error) {
console.error("Error subscribing to zaps:", error);
setZapsError(error.message);
setZapsLoading(false);
}
}
2024-08-13 14:42:36 -05:00
if (event && Object.keys(event).length > 0) {
subscribeToZaps();
}
2024-08-13 14:42:36 -05:00
return () => {
if (subscription) {
subscription.stop();
}
};
}, [event, ndk]);
2024-08-13 14:42:36 -05:00
return { zaps, zapsLoading, zapsError };
}