v28
v283w ago

Correct way to fetch trpc data on SSR and CSR

Hello, I am currently using trpc in my nextjs app router project and I am wondering what the best way of using trpc is with a mixture of SSR and CSR. The issue I'm having is that because I'm fetching the data on the server, it also fetches on the client which menas I'm making a request needlessly, and I'm not sure what the best way of dealing with this is. I have a page which is SSR rendered, so I fetch the data which will be used by the page:
"use server"

export default async function Applications({ params }: Props) {
const { guildId } = await params;
const applications = await api.application.getAll({ guildId });

return (
<HydrateClient>
<h1>Applications {guildId}</h1>
<Test applications={applications} />
</HydrateClient>
);
}
"use server"

export default async function Applications({ params }: Props) {
const { guildId } = await params;
const applications = await api.application.getAll({ guildId });

return (
<HydrateClient>
<h1>Applications {guildId}</h1>
<Test applications={applications} />
</HydrateClient>
);
}
"use client"

export const Test = ({ applications, guildId }: TestProps) => {
const { data, refetch } = api.application.getAll.useQuery(
{
guildId: guildId,
}
);
const [apps, setApps] = useState(applications);

useEffect(() => {
if (data) {
setApps(data);
}
}, [data, applications]);

return (
<div>
<h1>Test</h1>
{apps.map((application) => (
<div key={application.id}>{application.name}</div>
))}
<Button
onClick={async () => {
await refetch();
}}
>
refetch
</Button>
</div>
);
};
"use client"

export const Test = ({ applications, guildId }: TestProps) => {
const { data, refetch } = api.application.getAll.useQuery(
{
guildId: guildId,
}
);
const [apps, setApps] = useState(applications);

useEffect(() => {
if (data) {
setApps(data);
}
}, [data, applications]);

return (
<div>
<h1>Test</h1>
{apps.map((application) => (
<div key={application.id}>{application.name}</div>
))}
<Button
onClick={async () => {
await refetch();
}}
>
refetch
</Button>
</div>
);
};
0 Replies
No replies yetBe the first to reply to this messageJoin