#Server action
1 messages · Page 1 of 1 (latest)
Yes, you can fetch the current user in a client component using the server action file you provided. However, you need to ensure that the server action is properly imported and used in the client component. According to the Next.js documentation, Client Components can only import actions that use the module-level "use server" directive.
Here is how you can structure your code:
- Server Action File: Ensure that the server action file uses the
"use server"directive at the top.
// app/actions.ts
'use server';
import { getServerSession } from 'next-auth/next';
import { authOptions } from '@/pages/api/auth/[...nextauth]';
import prisma from '@/app/libs/prismadb';
export async function getSession() {
return await getServerSession(authOptions);
}
export default async function getCurrentUser() {
try {
const session = await getSession();
if (!session?.user?.email) {
return null;
}
const currentUser = await prisma.user.findUnique({
where: {
email: session.user.email as string,
},
});
if (!currentUser) {
return null;
}
return {
...currentUser,
createdAt: currentUser.createdAt.toISOString(),
updatedAt: currentUser.updatedAt.toISOString(),
emailVerified: currentUser.emailVerified?.toISOString() || null,
};
} catch (error: any) {
return null;
}
}
- Client Component: Import and use the server action in your client component.
// app/ui/client-component.tsx
'use client';
import { getCurrentUser } from '@/app/actions';
export default function ClientComponent() {
const handleFetchUser = async () => {
const user = await getCurrentUser();
console.log(user);
};
return (
<div>
<button onClick={handleFetchUser}>Fetch Current User</button>
</div>
);
}
By following this structure, you ensure that the server action is correctly imported and used in the client component. For more details, you can refer to the Next.js documentation on Server Actions and Mutations (https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions-and-mutations#convention).