Files
hristudio/src/context/active-study.tsx
Sean O'Connor 207f4d7fb8 chore(deps): Update dependencies and refactor API routes for improved error handling
- Updated various dependencies in package.json and pnpm-lock.yaml, including '@clerk/nextjs' to version 6.7.1 and several others for better performance and security.
- Refactored API routes to use Promise.resolve for context parameters, enhancing reliability in asynchronous contexts.
- Improved error handling in the dashboard and studies components, ensuring better user experience during data fetching.
- Removed unused favicon.ico file to clean up the project structure.
- Enhanced the dashboard components to utilize a new utility function for API URL fetching, promoting code reusability.
2024-12-05 11:52:22 -05:00

109 lines
3.0 KiB
TypeScript

'use client';
import { createContext, useContext, useEffect, useState, useCallback } from 'react';
import { usePathname, useRouter } from 'next/navigation';
interface Study {
id: number;
title: string;
description: string | null;
userId: string;
environment: string;
createdAt: Date;
updatedAt: Date | null;
permissions: string[];
}
interface ActiveStudyContextType {
activeStudy: Study | null;
setActiveStudy: (study: Study | null) => void;
studies: Study[];
isLoading: boolean;
error: string | null;
refreshStudies: () => Promise<void>;
}
const ActiveStudyContext = createContext<ActiveStudyContextType | undefined>(undefined);
export function ActiveStudyProvider({ children }: { children: React.ReactNode }) {
const [activeStudy, setActiveStudy] = useState<Study | null>(null);
const [studies, setStudies] = useState<Study[]>([]);
const [isLoading, setIsLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const pathname = usePathname();
const router = useRouter();
const fetchStudies = useCallback(async () => {
try {
const response = await fetch('/api/studies', {
method: 'GET',
headers: {
'Content-Type': 'application/json',
},
});
if (!response.ok) throw new Error('Failed to fetch studies');
const data = await response.json();
const studiesWithDates = (data.data || []).map((study: any) => ({
...study,
createdAt: new Date(study.createdAt),
updatedAt: study.updatedAt ? new Date(study.updatedAt) : null,
}));
setStudies(studiesWithDates);
if (studiesWithDates.length === 1 && !activeStudy) {
setActiveStudy(studiesWithDates[0]);
router.push(`/dashboard/studies/${studiesWithDates[0].id}`);
}
} catch (error) {
console.error('Error fetching studies:', error);
setError(error instanceof Error ? error.message : 'Failed to load studies');
} finally {
setIsLoading(false);
}
}, [router]);
useEffect(() => {
fetchStudies();
}, [fetchStudies]);
useEffect(() => {
const studyIdMatch = pathname.match(/\/dashboard\/studies\/(\d+)/);
if (studyIdMatch) {
const studyId = parseInt(studyIdMatch[1]);
const study = studies.find(s => s.id === studyId);
if (study && (!activeStudy || activeStudy.id !== study.id)) {
setActiveStudy(study);
}
} else if (!pathname.includes('/studies/new')) {
if (activeStudy) {
setActiveStudy(null);
}
}
}, [pathname, studies]);
const value = {
activeStudy,
setActiveStudy,
studies,
isLoading,
error,
refreshStudies: fetchStudies,
};
return (
<ActiveStudyContext.Provider value={value}>
{children}
</ActiveStudyContext.Provider>
);
}
export function useActiveStudy() {
const context = useContext(ActiveStudyContext);
if (context === undefined) {
throw new Error('useActiveStudy must be used within an ActiveStudyProvider');
}
return context;
}