Blog>
Snippets

Fetching Data on the Server with getServerSideProps

Use React Query's useQuery hook in combination with Next.js's getServerSideProps to fetch data server-side and pass it as props to a page component.
export async function getServerSideProps(context) {
  // Fetch your data here, e.g., from an API
  const response = await fetch('https://api.example.com/data');
  const data = await response.json();

  // Pass the data to the page via props
  return { props: { initialData: data } };
}
This code fetches data on the server using getServerSideProps. The fetched data is then passed as props to the component.
import { useQuery } from 'react-query';

export default function MyPage({ initialData }) {
  // Setup the useQuery hook
  const { data, isSuccess, isLoading } = useQuery('myData', async () => {
    // This function is a placeholder for your actual data fetching logic
    // if you need to fetch updated data on the client side
  }, {
    // Use initialData passed from getServerSideProps as the initial cache data
    initialData
  });

  // Render your component based on the fetched data
  return (
    <div>{isLoading ? <p>Loading...</p> : isSuccess ? <div>{JSON.stringify(data)}</div> : <p>Error</p>}</div>
  );
}
This component uses the useQuery hook from React Query to manage the server-side fetched data. The initialData prop from getServerSideProps is used as the initial state for the query cache.