Prefetching data on the server
To enable prefetching data on the server use the fetchHookData
function alongside addHookData
.
We also recommend using the handleError
function and to wrap the fetchHookData
call in a try/catch.
src/pages/[...path].js
import {
usePost,
fetchHookData,
addHookData,
handleError
} from '@headstartwp/next';
const params = { postType: ['post', 'page'] };
const SinglePostsPage = () => {
const { data } = usePost(params);
// when doing ssr/ssg data will always be available so handling loading/error state is optional
return (
<div>
<h2>{data?.post.title.rendered}</h2>
</div>
);
};
export default SinglePostsPage;
// or export async function getServerSideProps(context)
export async function getStaticProps(context) {
try {
const usePostHook = await fetchHookData(usePost.fetcher(), context, { params });
return addHookData([usePostHook], { myCustomProp: 'value' });
} catch (e) {
return handleError(e, context);
}
}
- The fetchHookData function receives a strategy, the Next.js context object and an object containing the params. The
params
must match the params passed to the hook, hence why it's been moved into a variable outside of theSinglePostsPage
component. - The addHookData receives an array of responses returned by
fetchHookData
and prepares that data to be returned to the page as props. If you need to pass additional props just pass them in the second argument. - The handleError function handles errors such as 404, redirects (when redirects are set to 404) among other things.
We recommend reviewing the starter project for more examples of prefetching data on the server.