GetServerSideProps Example NextJs
GetServerSideProps when used in Nextjs several things happen -
- Code placed within this function gets run only on the serverside
- Getserversideprops is run before the Page Component (note: this can used only on Page level)
- The page which contains this function would be Server Side Rendered (SSR - this would be marked with ssr symbol in the build production logs)
- Frontend does not have access this function, so business logic can be placed here.
Code example:
/**
*
* @param {*} jsonData
*
* This is the page component.
* Remember getServerSideProps can only be used on Page level!
*
*
*/
export default async function Home ({ jsonData }) {
// destructured jsonData which was passed from gerserversideprops
// note this is in JSON , so make sure to parse it
console.log(jsonData, "data");
// parsing the json data - with this we have a workable object (it could be any array , object, arary of objects & so on)
const parsedBlogPosts = await JSON.parse(jsonData)
return (
<>
<div className="container">
{parsedBlogPosts.map((blogPost) => (
<h2 key={blogPost._id} >{blogPost?.heading}</h2>
// if parsedBlogPosts has valid array of objects with heading property , it would rendered on page
))}
{parsedBlogPosts.length === 0 && <h2>No posts yet /Loading</h2>
// if the array is empty this conditional would be triggered
}
</div>
</>
);
}
const domain = "thirdpartyapi.com";
/**
*
* @returns []
*
* getServerSideProps executes first and sets data to the page component
*
*/
export async function getServerSideProps() {
// Fetch data from external API
// a simple get request
// just assume you receive an array of posts - in json
let jsonData
try {
jsonData = await fetch(domain + "/api/blog-post/get-all");
console.log(jsonData);
} catch (error) {
console.log("error", error);
jsonData =[]
}
// Pass data to the page via props
return { props: { jsonData } };
}
Note:
In this example I have kept the response which the getServerSideProps fetched as json without parsing on the server side.
"jsonData" is parsed in the frontend (client side) and stored to "parsedBlogPosts".
Read about how to use getServerSideProps(contenxt) here .
Comments
Post a Comment
Oof!