How do I fetch from server side with useMutation?
Hello, I'm trying to do a server side fetch from the mutations that I made in the backend of my t3 app but I'm struggling to understand some things can someone help me please? I'm trying to pass the data from both the queries as props. What would be the most optimal approach to this?
This is my code
11 Replies
useMutation
and useQuery
should only be used inside your components. tRPC provides helpers for fetching data on the server: https://trpc.io/docs/client/nextjs/ssgStatic Site Generation | tRPC
Reference project//github.com/trpc/examples-next-prisma-todomvc
can you point specifically what component/library/file should I be importing in order to re-use the mutations that I made on the api or am I forced to import prisma and re-do the queries inside getstaticprops?
it's spelled out for you on that page - use
createServerSideHelpers
and prefetch
in getStaticProps
All your mutations and stuff stay the same, you're just using prefetch
instead of useQuery
Also from the looks of things you're using mutations to fetch data - don't do that
getUserPendingSubscriptions
and getUserPendingSubscriptions
sound like things that should definitely be queriesOk so I did the create server side helpers object, it asked me to send context whith session and prisma and I did(I think so) but it still doesn't work, it's not recognizing the methods, what am I missing ?
They aren't available as
helpers
will only contain queries, which those procedures should almost certainly be changed toI previously had them as queries but they would refresh my page everytime the window focused and I couldn't figure out how to remove that also so that's why they were made into mutations
so there's no way to do it without changing them to queries?
The correct move is to change them to queries and fix the refresh-on-focus behaviour at it's cause
It's crucial to understand that
useQuery
and the like arent tRPC things, they're react query things, and react query's default behaviour is to refetch queries when the window is refocusedYou can disable window focus refetching at a per-query level or entirely: https://tanstack.com/query/v4/docs/react/guides/window-focus-refetching
Window Focus Refetching | TanStack Query Docs
If a user leaves your application and returns and the query data is stale, TanStack Query automatically requests fresh data for you in the background. You can disable this globally or per-query using the refetchOnWindowFocus option:
Disabling Globally
I'm guessing this is it? but how do I get the data from the page itself?
I get the data but it's undefined and it shouldn't be
Just do a regular
useQuery
, the data should be automatically hydrated + inserted into the query
Make sure you've wrapped your default export in pages/_app
in withTRPC
nice now it works, thanks a lot for the help. You're a hero.