'use client'; import { useEffect, useState } from "react"; import { Button } from "~/components/ui/button"; import { Card, CardHeader, CardTitle, CardContent } from "~/components/ui/card"; import { Input } from "~/components/ui/input"; import { Label } from "~/components/ui/label"; import { PlusIcon, Trash2Icon } from "lucide-react"; import { Select, SelectTrigger, SelectValue, SelectContent, SelectItem, SelectLabel, } from "~/components/ui/select"; interface Study { id: number; title: string; } interface Participant { id: number; name: string; studyId: number; } export default function Participants() { const [studies, setStudies] = useState([]); const [participants, setParticipants] = useState([]); const [selectedStudyId, setSelectedStudyId] = useState(null); const [participantName, setParticipantName] = useState(""); const [loading, setLoading] = useState(true); useEffect(() => { fetchStudies(); }, []); const fetchStudies = async () => { try { const response = await fetch('/api/studies'); const data = await response.json(); setStudies(data); } catch (error) { console.error('Error fetching studies:', error); } finally { setLoading(false); } }; const fetchParticipants = async (studyId: number) => { try { const response = await fetch(`/api/participants?studyId=${studyId}`); const data = await response.json(); setParticipants(data); } catch (error) { console.error('Error fetching participants:', error); } }; const handleStudyChange = (studyId: string) => { const id = parseInt(studyId); // Convert the string to a number setSelectedStudyId(id); fetchParticipants(id); }; const addParticipant = async (e: React.FormEvent) => { e.preventDefault(); if (!selectedStudyId) return; try { const response = await fetch(`/api/participants`, { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ name: participantName, studyId: selectedStudyId, }), }); if (response.ok) { const newParticipant = await response.json(); setParticipants([...participants, newParticipant]); setParticipantName(""); } else { console.error('Error adding participant:', response.statusText); } } catch (error) { console.error('Error adding participant:', error); } }; const deleteParticipant = async (id: number) => { try { const response = await fetch(`/api/participants/${id}`, { method: 'DELETE', }); if (response.ok) { setParticipants(participants.filter(participant => participant.id !== id)); } else { console.error('Error deleting participant:', response.statusText); } } catch (error) { console.error('Error deleting participant:', error); } }; if (loading) { return
Loading...
; } return (

Manage Participants

Add New Participant
setParticipantName(e.target.value)} required />

Participant List

    {participants.map((participant) => (
  • {participant.name}
  • ))}
); }