T
TanStack3y ago
stormy-gold

react-query + Next.js + ssg

Hi everyone I have a question… is it possible to use react query , nextjs and ssg where api server is nextjs? I have found this: https://tanstack.com/query/v4/docs/react/guides/ssr But in this example it fetch data from external api …
SSR | TanStack Query Docs
React Query supports two ways of prefetching data on the server and passing that to the queryClient. Prefetch the data yourself and pass it in as initialData
8 Replies
fair-rose
fair-rose3y ago
sure, why not?
stormy-gold
stormy-goldOP3y ago
Ehi, thak you first of all thank you for the answer.... my question is how can call an endpoint at build time where the api server is himself (next)... ? At build time api server is not up...
fair-rose
fair-rose3y ago
right, I think calling api endpoints from getStaticProps was never recommended either. You'd want to just refactor the content of the api call to a functon that you can invoke from both places
stormy-gold
stormy-goldOP3y ago
You mean for example here: https://tanstack.com/query/v4/docs/react/guides/ssr#using-hydration getPost could be a directly call to database?
SSR | TanStack Query Docs
React Query supports two ways of prefetching data on the server and passing that to the queryClient. Prefetch the data yourself and pass it in as initialData
fair-rose
fair-rose3y ago
yes on the server, it would be:
await queryClient.prefetchQuery('posts', readPostsFromDB)
await queryClient.prefetchQuery('posts', readPostsFromDB)
stormy-gold
stormy-goldOP3y ago
ok but on client side i can call api.... so quickly recap:
// pages/posts.jsx
import { dehydrate, QueryClient, useQuery } from '@tanstack/react-query'

export async function getStaticProps() {
const queryClient = new QueryClient()

await queryClient.prefetchQuery(['posts'], readPostsFromDB)

return {
props: {
dehydratedState: dehydrate(queryClient),
},
}
}

function Posts() {
// This useQuery could just as well happen in some deeper child to
// the "Posts"-page, data will be available immediately either way
const { data } = useQuery({ queryKey: ['posts'], queryFn: readPostsFromApi })


// ...
}
// pages/posts.jsx
import { dehydrate, QueryClient, useQuery } from '@tanstack/react-query'

export async function getStaticProps() {
const queryClient = new QueryClient()

await queryClient.prefetchQuery(['posts'], readPostsFromDB)

return {
props: {
dehydratedState: dehydrate(queryClient),
},
}
}

function Posts() {
// This useQuery could just as well happen in some deeper child to
// the "Posts"-page, data will be available immediately either way
const { data } = useQuery({ queryKey: ['posts'], queryFn: readPostsFromApi })


// ...
}
fair-rose
fair-rose3y ago
Yes, that's good 👍
stormy-gold
stormy-goldOP3y ago
thanks very much

Did you find this page helpful?