0

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!

5
  • can you try and see what you get doing this: const { data} = useQuery(['threads', { token: stateToken }], QueryThreads) console.log(data) Commented Jan 13, 2021 at 18:19
  • @Sir Codes Alot says that data is undefined Commented Jan 13, 2021 at 18:39
  • 2
    const { isLoading,error,data} = useQuery(['threads', { token: stateToken }], QueryThreads) if(isLoading) return "Loading..."; if(error) return "Error...:; console.log(response.data) If that doesn't work, can you put an example up on codesandbox.io to troubleshoot Commented Jan 13, 2021 at 18:53
  • @Sir Codes Alot Thanks! It works! I just needed to use isLoading and isError! Commented Jan 13, 2021 at 22:16
  • have you done this const queryClient = new QueryClient(); at the _app.js? Commented Apr 1, 2021 at 21:27

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.