Fetch data for client component
Answered
Siamese posted this in #help-forum
SiameseOP
// profile-action.tsx
"use server";
import { headers } from "next/headers";
import { auth } from "@/server/auth";
import { prisma } from "@/server/prisma";
import { type Profile } from "@prisma/client";
export const getProfileAction = async (): Promise<Profile | null> => {
try {
const session = await auth.api.getSession({
headers: await headers(),
});
if (!session) return null;
return await prisma.profile.findFirst({
where: { userId: session.user.id },
include: { user: true },
});
} catch (error) {
console.error("Error fetching profile:", error);
return null;
}
};
// use-profile.tsx
import { useEffect, useState } from "react";
import { getProfileAction } from "@/app/actions/profile";
import { Profile } from "@prisma/client";
export const useProfile = () => {
const [profile, setProfile] = useState<Profile | null>(null);
const [isLoading, setLoading] = useState<boolean>(true);
const [isError, setError] = useState<string | null>(null);
const fetchProfile = async () => {
try {
const res = await getProfileAction();
if (!res) throw new Error("Profile not found.");
setProfile(res);
} catch (err: any) {
setError(err.message || "Error fetching profile.");
} finally {
setLoading(false);
}
};
useEffect(() => {
fetchProfile();
}, []);
return { profile, isLoading, isError, refetch: fetchProfile };
};
So the doubt is, this is how im fetching profile data by using a server action and a hook, so is this a efficient way or there is any other recomended way to do the same thing ?
Answered by Asian black bear
Dont use server actions for data fetching. Use server components and pass data down to client components. If you have to perform client side data fetching which is fairly rare then use react-query against an API route of yours.
1 Reply
Asian black bear
Dont use server actions for data fetching. Use server components and pass data down to client components. If you have to perform client side data fetching which is fairly rare then use react-query against an API route of yours.
Answer