2024-08-04 17:02:34 -05:00
|
|
|
import { useState, useEffect } from 'react';
|
|
|
|
import { useQuery } from '@tanstack/react-query';
|
|
|
|
import { useNDKContext } from '@/context/NDKContext';
|
|
|
|
|
2024-08-04 18:00:59 -05:00
|
|
|
export function useCoursesZapsQuery({ event }) {
|
2024-08-04 17:02:34 -05:00
|
|
|
const [isClient, setIsClient] = useState(false);
|
|
|
|
const ndk = useNDKContext();
|
|
|
|
|
|
|
|
useEffect(() => {
|
|
|
|
setIsClient(true);
|
|
|
|
}, []);
|
|
|
|
|
2024-08-04 18:00:59 -05:00
|
|
|
const fetchZapsFromNDK = async (event) => {
|
|
|
|
if (!ndk) {
|
|
|
|
console.error('NDK instance is null');
|
|
|
|
return [];
|
|
|
|
}
|
|
|
|
|
|
|
|
if (!event) {
|
|
|
|
console.error('No event provided');
|
|
|
|
return [];
|
|
|
|
}
|
|
|
|
|
2024-08-04 17:02:34 -05:00
|
|
|
try {
|
|
|
|
await ndk.connect();
|
|
|
|
let zaps = [];
|
|
|
|
|
2024-08-04 18:00:59 -05:00
|
|
|
const filters = [{ kinds: [9735], "#e": [event.id] }, { kinds: [9735], "#a": [`${event.kind}:${event.id}:${event.d}`] }];
|
2024-08-04 17:02:34 -05:00
|
|
|
|
2024-08-04 18:00:59 -05:00
|
|
|
for (const filter of filters) {
|
|
|
|
const zapEvents = await ndk.fetchEvents(filter);
|
|
|
|
zapEvents.forEach(zap => zaps.push(zap));
|
2024-08-04 17:02:34 -05:00
|
|
|
}
|
2024-08-04 18:00:59 -05:00
|
|
|
|
2024-08-04 17:02:34 -05:00
|
|
|
return zaps;
|
|
|
|
} catch (error) {
|
|
|
|
console.error('Error fetching zaps from NDK:', error);
|
|
|
|
return [];
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
const { data: zaps, isLoading: zapsLoading, error: zapsError, refetch: refetchZaps } = useQuery({
|
2024-08-04 18:00:59 -05:00
|
|
|
queryKey: ['coursesZaps', isClient, event],
|
|
|
|
queryFn: () => fetchZapsFromNDK(event),
|
2024-08-04 17:02:34 -05:00
|
|
|
staleTime: 1000 * 60 * 3, // 3 minutes
|
|
|
|
cacheTime: 1000 * 60 * 60, // 1 hour
|
|
|
|
enabled: isClient,
|
2024-08-04 18:00:59 -05:00
|
|
|
});
|
2024-08-04 17:02:34 -05:00
|
|
|
|
|
|
|
return { zaps, zapsLoading, zapsError, refetchZaps }
|
2024-08-04 18:00:59 -05:00
|
|
|
}
|