I am trying to fetch data to my dashboard component in SSR but get undefined
Are there any solution to fetch data properly?
Here is my code of Dashboard component:
import Container from "./Container";
import { getServerSession } from "next-auth/next";
import { authConfig } from "../../lib/auth";
import { getServer } from "@/app/api/servers";
export const getServerSideProps = async () => {
const session = await getServerSession(authConfig); // Wrap in getServerSession
const userId = session?.user.id;
const serverData = await getServer(userId); // Pass userId if needed
return { props: { serverData } }; // Return object with serverData prop
};
const Dashboard = ({ serverData }) => {
return (
<div className="w-full min-h-full p-4 border-b-2 border-t-2 border-t-white border-b-cyan-100 shadow-lg mb-8 h-80 min-h-72">
<div className="w-full h-full flex flex-row gap-5">
<Container serverData={serverdata} />
</div>
</div>
);
};
export default Dashboard;
Here is the code of my getServer function:
export const getServer = async (userId: string) => {
console.log("getServer", userId);
try {
// Find servers belonging to the user
const servers = await prisma.server.findMany({
where: {
userId: userId,
},
});
return servers;
} catch (error) {
// Handle any errors
console.error("Error retrieving servers:", error);
throw error; // Re-throw the error for the caller to handle
}
};
2
Answers
Just create async function to fetch data and call it in your Page.
Next +13 doesn’t support getServerSideProps as old versions.
If you don’t use hooks like useState in your component or page, you can fetch data using server components like this: