React Query with SSR(NextJS V12) Api Calling Issue.
Currently I am using
getInitialProps to fetch my data. And after fetching I am dehydrating the data, it is working fine as expected. But the issue is when I am doing Client side navigation, my Api calling is happening (from useQuery). But if I enable shallow routing then the API calling is not happening. Now how can I disable API calling without using shallow ?
PS: I've already tried some solution from https://github.com/vercel/next.js/discussions/19611. if (typeof window !== 'undefined') {
return {
props: {},
};
}
. Still API Calling is happening.
Thanks in advance.15 Replies
helpful-purple•3y ago
Hi. Never used SSR but looks like a missing staleTime on your query to limit fetching?
extended-salmonOP•3y ago
I've set
staleTime to Infinityhelpful-purple•3y ago
Ok. Maybe an unstable queryclient. Could you setup a reproduction somewhere?
extended-salmonOP•3y ago
sure... will share the link
extended-salmonOP•3y ago
https://stackblitz.com/edit/nextjs-1fowhs?file=pages/smallcases/[...path].jsx
Please check this link
NextJS+ReactQuery+SSR - StackBlitz
The React framework for production.
helpful-purple•3y ago
Not real solution for now… But one question
getInitialProps should return the props right?
helpful-purple•3y ago
Data Fetching: getInitialProps | Next.js
Enable Server-Side Rendering in a page and do initial data population with
getInitialProps.helpful-purple•3y ago
Isn't there an extra
props in your function?
helpful-purple•3y ago
Shoudn't it be:

extended-salmonOP•3y ago
oops right, but this is not the reason right ?
helpful-purple•3y ago
🤷 I'm not sure. As mentioned, I've never used NextJS so unsure I will be able to help you on this one.
optimistic-gold•3y ago
getInitialProps runs on the server and the client. You've mentioned the typeof window check but I don't see it anywhere in your example
what I do is I use getServerSideProps with a similar bailout:
this works fine (only does something in gSSP on the first real server render call), but the call to gSSP is still made on every link transition, but it doesn't do anything so it's sufficiently fast for me.
The real long term solution is probably to use next13 and the app directoryhelpful-purple•3y ago
"getInitialProps runs on the server and the client." that's the part I was missing 😅
optimistic-gold•3y ago
That's also why they don't recommend using it 🙂
extended-salmonOP•3y ago
Perfect
Now this is working
1. For client side returning empty object
2. return
dehydratedState directly, (earlier it was inside props)
Page.getInitialProps = async () => {
if (typeof window !== 'undefined') {
return {};
}
const queryClient = new QueryClient();
await queryClient.prefetchQuery(['posts'], getPosts);
return {
dehydratedState: dehydrate(queryClient),
};
};
Thanks @TkDodo 🔮 @glabat