plebdevs/src/hooks/nostrQueries/content/useWorkshopsQuery.js

60 lines
2.2 KiB
JavaScript
Raw Normal View History

import { useState, useEffect } from 'react';
import { useQuery } from '@tanstack/react-query';
import { useNDKContext } from '@/context/NDKContext';
2024-08-09 14:28:57 -05:00
import axios from 'axios';
2024-08-08 16:29:16 -05:00
const AUTHOR_PUBKEY = process.env.NEXT_PUBLIC_AUTHOR_PUBKEY;
export function useWorkshopsQuery() {
const [isClient, setIsClient] = useState(false);
const ndk = useNDKContext();
useEffect(() => {
setIsClient(true);
}, []);
2024-08-09 14:28:57 -05:00
const hasRequiredProperties = (event, contentIds) => {
2024-08-08 16:29:16 -05:00
const hasPlebDevs = event.tags.some(([tag, value]) => tag === "t" && value === "plebdevs");
const hasWorkshop = event.tags.some(([tag, value]) => tag === "t" && value === "workshop");
2024-08-09 14:28:57 -05:00
const hasId = event.tags.some(([tag, value]) => tag === "d" && contentIds.includes(value));
2024-08-08 16:29:16 -05:00
return hasPlebDevs && hasWorkshop && hasId;
};
const fetchWorkshopsFromNDK = async () => {
try {
2024-08-09 14:28:57 -05:00
const response = await axios.get(`/api/content/all`);
const contentIds = response.data;
if (!contentIds || contentIds.length === 0) {
console.log('No content IDs found');
return []; // Return early if no content IDs are found
2024-08-08 16:29:16 -05:00
}
2024-08-09 14:28:57 -05:00
2024-08-08 16:29:16 -05:00
await ndk.connect();
const filter = { kinds: [30023, 30402], authors: [AUTHOR_PUBKEY] };
const events = await ndk.fetchEvents(filter);
if (events && events.size > 0) {
const eventsArray = Array.from(events);
2024-08-09 14:28:57 -05:00
const workshops = eventsArray.filter(event => hasRequiredProperties(event, contentIds));
2024-08-08 16:29:16 -05:00
return workshops;
}
return [];
} catch (error) {
console.error('Error fetching workshops from NDK:', error);
return [];
}
};
const { data: workshops, isLoading: workshopsLoading, error: workshopsError, refetch: refetchWorkshops } = useQuery({
queryKey: ['workshops', isClient],
queryFn: fetchWorkshopsFromNDK,
2024-08-09 14:28:57 -05:00
// staleTime: 1000 * 60 * 30, // 30 minutes
// refetchInterval: 1000 * 60 * 30, // 30 minutes
2024-08-08 16:29:16 -05:00
enabled: isClient,
});
return { workshops, workshopsLoading, workshopsError, refetchWorkshops };
}