TanStackT
TanStack3y ago
1 reply
efficient-indigo

prerender react query data on server

'use client'
import React from 'react'
import { useQuery } from '@tanstack/react-query'
import axios from 'axios';
const question = () => {

  const { data, isLoading } = useQuery({
    queryKey: ['QUESTION'],
    queryFn: async () => {
      const response = await axios.get('http://localhost:8081/api/question/getQuestionTest');
      return response.data.question;
    }
  })
  if(isLoading) {
    return (
      <main className="flex min-h-screen flex-col items-center justify-between p-24">
        <p>
          Loading...
        </p>
      </main>
    )
  }

  return (
    <main className="flex min-h-screen flex-col items-center justify-between p-24">
      <p>
        {
          data && (
            <div>
              <h2>{data.question}</h2>
            </div>
          )
        }
      </p>
    </main>
  )
}

export default question


import { dehydrate, HydrationBoundary } from '@tanstack/react-query';
import getQueryClient from '@/lib/getQueryClient';
import Question from '@/components/question/index';

export default async function index() {

  const queryClient = getQueryClient()
  await queryClient.prefetchQuery({
    querykey: ['QUESTION'],
    queryFn: async () => {
      const response = await axios.get('http://localhost:8081/api/question/getQuestionTest');
      return response.data.question;
    }
  })
  const dehydratedState = dehydrate(queryClient)

  return (
    <main>
      <h1 className='mt-10 p-10 w-full m-auto text-center border rounded-full' >
        Question Page
      </h1>
      <HydrationBoundary state={dehydratedState}>
        <Question />
      </HydrationBoundary>
    </main>
  )
}


correct me if i am wrong, this query fetches data on client side which is not what i want but i want this query data to be pre rendered on server due to SEO concerns. we can simply just do that by fetch but with with react-query i want that data to be prerendered on server.
Was this page helpful?