[Beginner] fetching data via prisma in a component
Unanswered
American black bear posted this in #help-forum
American black bearOP
Hi, Im trying to fetch some data (an object called "event" ) from prisma from a server and use it in a component:
this is what my code looks like,
events.actions.ts
this is what my code looks like,
events.actions.ts
export async function getEventDetails(id: string) {
const event = await prisma.event.findUnique({ where: { id: id } });
return event;
}
4 Replies
American black bearOP
component file (tsx):
"use client";
import eventData from "@/data/eventData";
import { useParams } from "next/navigation";
import { use, useEffect, useState } from "react";
import { getEventDetails } from "@/events.actions";
import Image from "next/image";
export default function EventPhoto() {
const params = useParams();
let { id } = params;
// const event = eventData.find((event) => event.id.toString() === id);
const [event, setEvent] = useState(null);
useEffect(() => {
async function fetchEvent() {
const event = await getEventDetails(id);
setEvent(event);
}
fetchEvent();
}
if (!event) {
return <div>Event not found</div>;
}
const { eventPhotos } = event;
return (
<div className="p-5">
<h1 className="text-center text-4xl md:text-5xl font-bold mb-8">
{event.title}
</h1>
<div className="grid grid-cols-1 lg:px-16 md:grid-cols-3 gap-4">
{eventPhotos && eventPhotos.length > 0 ? (
eventPhotos.map((photo, index) => (
<div key={index} className="relative w-full h-64">
<Image
src={photo}
alt={`Event Photo ${index + 1}`}
layout="fill"
objectFit="cover"
className="rounded"
/>
</div>
))
) : (
<p>No photos available for this event.</p>
)}
</div>
</div>
);
}
the
// const event = eventData.find((event) => event.id.toString() === id);
is temporary, hardcoded data, i am trying to replace it with the getEventDetails
function, but there is something wrong with the typescripti have no idea where to go from here, please help a brother. i am very new to nextjs so excuse the dumb questions 🙏🏻