learnbydoing
learnbydoing

Reputation: 509

Next.js + React Query (data is undefined)

This is the first time to use React Query with Next.

My problem is this, I am trying to make a query with useQuery, but the result of my "data", which I called "response" is undefined.

I don't understand why I'm making an error, because the code I have is basically what I have done so far.

My app.js code:

const App = ({ Component, pageProps }) => {
  return (
    <>
      <QueryClientProvider client={queryClient}>
        <Hydrate state={pageProps.dehydratedState}>
          <Component {...pageProps} />
        </Hydrate>
      </QueryClientProvider>
    </>
  )
}

My threads.js code:

const { data: response } = useQuery(['threads', { token: stateToken }], QueryThreads)
console.log(response.data)

I hope you have a great day!

Upvotes: 0

Views: 2419

Answers (1)

Dhammika
Dhammika

Reputation: 81

React Query supports two ways of prefetching data

  1. using 'initialData'
  2. using hydration method

As you have used hydration method you can use getServerSideProps() to prefetch data.


export async function getServerSideProps() {

  const queryClient =new QueryClient();
  await queryClient.prefetchQuery (['threads', { token: stateToken }], QueryThreads)

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

Refer React Query docs.

Upvotes: 1

Related Questions