NextJS server-side rendering utilizing front-end React Query integration
P粉790187507
P粉790187507 2024-03-28 15:53:57
0
2
454

I currently have the following React query implementation:

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

I pass the returned results to the custom component:

<Results foundRecords={data}/>

I'm passing the initial search results into my parent page component so that search engine crawlers can see the results on the initial page load (if the request is made on the client side - i.e. using useQuery( )).

In this case, what is the best way to integrate the initial search value passed into the component (via NextJS's getServerSideProps()) with useQuery() ?

From the top of my head it looks 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}/>   
    )
}

P粉790187507
P粉790187507

reply all(2)
P粉726133917

In order to get Google crawler results, you will need to use the metadata provided in the title and description, and you will also need to submit your domain name in the Google Console

export default function Mypage({user}) {
    
      return (
        
          
            
            
            
            My page
            
            //Open Graph meta tags...
          
          Home>
        >) 
 }
    
    
export async function getServerSideProps ({ req }) { 
  const user ={...}
  return {props: {user: user}} 
}
P粉799885311

The documentation recommends putting the data into useQuery's initialData. You can then continue using the 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 (
           
    )
}
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template