skip to Main Content

I currently have the following React Query implementation:

const { data, isSuccess, isLoading } = useQuery(['myQuery', myParams], async () => {
    return myAjaxCall(myParams);
}, {
    cacheTime: 0
});

And I pass the results returned into a custom component:

<Results foundRecords={data}/>

I am in the process of passing the initial search results into my parent page component so that search engine crawlers are able to see the results on initial page load (search engine bots like Google’s web crawler cannot see the initial search results if the requests are made client-side – ie. with useQuery()).

In this scenario, what’s the best way for me to integrate the initial search value I pass into my component (via NextJS’ getServerSideProps()) with a useQuery() implementation?

Off of the top of my head, it would look something like:

export async function getServerSideProps(context){
    ...
    return {
       initialData: ....
    }
}

export default function MyPage({initialData}){
    const { data, isSuccess, isLoading } = useQuery(['myQuery', myParams], async () => {
        return myAjaxCall(myParams);
    }, {
        cacheTime: 0
    });

    return (
        <Results foundRecords={initialData || data}/>   
    )
}

2

Answers


  1. In order to get the result for the Google crawlers you need to use Metadata where in your title and descriptions are provided also you need to submit your domain name in Google console

    export default function Mypage({user}) {
        
          return (
            <>
              <Head>
                <meta charSet="utf-8" />
                <link rel="icon" href="https://www.sample.com/favicon.ico" />
                <meta name="viewport" content="width=device-width, initial-scale=1" />
                <title>My page</title>
                <meta name="description" content="this is my page description" />
                //Open Graph meta tags...
              </Head>
              <>Home</>
            </>) 
     }
        
        
    export async function getServerSideProps ({ req }) { 
      const user ={...}
      return {props: {user: user}} 
    }
    
    Login or Signup to reply.
  2. The docs recommend to put the data into initialData of useQuery. Then, you can just continue to use data returned from useQuery:

    export async function getServerSideProps(context){
        ...
        return {
           initialData: ....
        }
    }
    
    export default function MyPage({initialData}){
        const { data, isSuccess, isLoading } = useQuery(['myQuery', myParams], async () => {
            return myAjaxCall(myParams);
        }, {
            cacheTime: 0,
            initialData
        });
    
        return (
            <Results foundRecords={data}/>   
        )
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search