![](https://wiki.supercombo.gg/images/2/2a/SSBM_Marth_Portrait.png)
@ Marth
2024-08-09 14:53:43
To prevent the contentIds from being undefined and causing an error, you can add handling to check if contentIds is defined before using it. Additionally, ensure contentIds has been fetched and is not in the loading state before proceeding with the fetchResourcesFromNDK function. Here is the updated useResourcesQuery with the necessary error handling
```js
import { useState, useEffect } from 'react';
import { useQuery } from '@tanstack/react-query';
import { useNDKContext } from '@/context/NDKContext';
import { useContentIdsQuery } from '@/hooks/apiQueries/useContentIdsQuery';
const AUTHOR_PUBKEY = process.env.NEXT_PUBLIC_AUTHOR_PUBKEY;
export function useResourcesQuery() {
const [isClient, setIsClient] = useState(false);
const { contentIds, contentIdsLoading, contentIdsError, refetchContentIds } = useContentIdsQuery();
const ndk = useNDKContext();
useEffect(() => {
setIsClient(true);
}, []);
useEffect(() => {
refetchContentIds();
}, [refetchContentIds]);
const hasRequiredProperties = (event) => {
if (!contentIds) {
return false;
}
const hasPlebDevs = event.tags.some(([tag, value]) => tag === "t" && value === "plebdevs");
const hasWorkshop = event.tags.some(([tag, value]) => tag === "t" && value === "resource");
const hasId = contentIds.includes(event.id);
return hasPlebDevs && hasWorkshop && hasId;
};
const fetchResourcesFromNDK = async () => {
try {
if (contentIdsLoading) {
return []; // or a loading state indication
}
if (contentIdsError) {
console.error('Error fetching content IDs:', contentIdsError);
return [];
}
if (!contentIds) {
return [];
}
console.log('Fetching workshops from NDK');
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);
console.log('eventsArray', eventsArray);
const resources = eventsArray.filter(event => hasRequiredProperties(event));
return resources;
}
return [];
} catch (error) {
console.error('Error fetching workshops from NDK:', error);
return [];
}
};
const { data: resources, isLoading: resourcesLoading, error: resourcesError, refetch: refetchResources } = useQuery({
queryKey: ['resources', isClient],
queryFn: fetchResourcesFromNDK,
staleTime: 1000 * 60 * 30, // 30 minutes
refetchInterval: 1000 * 60 * 30, // 30 minutes
enabled: isClient,
});
return { resources, resourcesLoading, resourcesError, refetchResources };
}
```
Explanation:
Error Handling for contentIds:
Added checks to ensure contentIds is defined before using it.
If contentIds is still loading or an error occurred while fetching contentIds, handle these cases appropriately by returning empty arrays or logging the error.
Loading State Check:
If contentIds is still loading, the fetchResourcesFromNDK function will return an empty array or indicate a loading state.
Error Check:
If there's an error in fetching contentIds, log the error and return an empty array to avoid breaking the application flow.
Apply the Same Handling to useCoursesQuery
Similarly, you can apply the same error handling and checks in the useCoursesQuery function:
```js
import { useState, useEffect } from 'react';
import { useQuery } from '@tanstack/react-query';
import { useNDKContext } from '@/context/NDKContext';
import { useContentIdsQuery } from '@/hooks/apiQueries/useContentIdsQuery';
const AUTHOR_PUBKEY = process.env.NEXT_PUBLIC_AUTHOR_PUBKEY;
export function useCoursesQuery() {
const [isClient, setIsClient] = useState(false);
const { contentIds, contentIdsLoading, contentIdsError, refetchContentIds } = useContentIdsQuery();
const ndk = useNDKContext();
useEffect(() => {
setIsClient(true);
}, []);
useEffect(() => {
refetchContentIds();
}, [refetchContentIds]);
const hasRequiredProperties = (event) => {
if (!contentIds) {
return false;
}
const hasCourseTag = event.tags.some(([tag, value]) => tag === "t" && value === "course");
const hasId = contentIds.includes(event.id);
return hasCourseTag && hasId;
};
const fetchCoursesFromNDK = async () => {
try {
if (contentIdsLoading) {
return []; // or a loading state indication
}
if (contentIdsError) {
console.error('Error fetching content IDs:', contentIdsError);
return [];
}
if (!contentIds) {
return [];
}
console.log('Fetching courses from NDK');
await ndk.connect();
const filter = { kinds: [30004], authors: [AUTHOR_PUBKEY] };
const events = await ndk.fetchEvents(filter);
if (events && events.size > 0) {
const eventsArray = Array.from(events);
console.log('eventsArray', eventsArray);
const courses = eventsArray.filter(event => hasRequiredProperties(event));
return courses;
}
return [];
} catch (error) {
console.error('Error fetching courses from NDK:', error);
return [];
}
};
const { data: courses, isLoading: coursesLoading, error: coursesError, refetch: refetchCourses } = useQuery({
queryKey: ['courses', isClient],
queryFn: fetchCoursesFromNDK,
staleTime: 1000 * 60 * 30, // 30 minutes
refetchInterval: 1000 * 60 * 30, // 30 minutes
enabled: isClient,
});
return { courses, coursesLoading, coursesError, refetchCourses };
}
```
By incorporating these changes, you should be able to prevent errors related to contentIds being undefined and ensure a smoother data-fetching process.