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

56 lines
1.9 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-09-17 13:55:51 -05:00
import appConfig from "@/config/appConfig";
export function useCoursesQuery() {
const [isClient, setIsClient] = useState(false);
const {ndk, addSigner} = useNDKContext();
useEffect(() => {
setIsClient(true);
}, []);
2024-08-09 14:28:57 -05:00
const hasRequiredProperties = (event, contentIds) => {
const hasId = event.tags.some(([tag, value]) => tag === "d" && contentIds.includes(value));
return hasId;
2024-08-08 16:29:16 -05:00
};
const fetchCoursesFromNDK = 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) {
return []; // Return early if no content IDs are found
2024-08-08 16:29:16 -05:00
}
await ndk.connect();
2024-08-08 16:29:16 -05:00
2024-09-17 13:55:51 -05:00
const filter = { kinds: [30004], authors: appConfig.authorPubkeys };
const events = await ndk.fetchEvents(filter);
2024-08-08 16:29:16 -05:00
if (events && events.size > 0) {
const eventsArray = Array.from(events);
2024-08-09 14:28:57 -05:00
const courses = eventsArray.filter(event => hasRequiredProperties(event, contentIds));
2024-08-08 16:29:16 -05:00
return courses;
}
return [];
} catch (error) {
2024-08-08 16:29:16 -05:00
console.error('Error fetching courses from NDK:', error);
return [];
}
2024-08-08 16:29:16 -05:00
};
const { data: courses, isLoading: coursesLoading, error: coursesError, refetch: refetchCourses } = useQuery({
queryKey: ['courses', isClient],
queryFn: fetchCoursesFromNDK,
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 { courses, coursesLoading, coursesError, refetchCourses };
}