I'm building a social media app using Next.js Sanity.
In a social media app, the data is in constant change as users add comments, likes, etc so it would make sense to use getServerSideProps
for SSR since the data displayed should be updated on each request right?
But how can I handle the dynamic routes for let's say, a user's profile Page, a post, etc? The docs explain that for dynamic routes I should use getStaticPaths
and getStaticProps
but that doesn't guarantee that the data for a user's profile or post will be updated since it's statically generated.
What's the proper way to work this out?
CodePudding user response:
Using getServerSideProps
gives you access to the context parameter of that function which will have a params
property that contains your dynamic route. So for example, if you want to have a user's profile at /user/{handle}
, you could create the following directory structure:
pages/
user/
[handle].js
The in your [handle].js
file (yes, the filename has square brackets), you would do something like this:
export default function UserHandlePage({ handle }) {
return (<p>Handle: ${handle}</p>)
}
export async function getServerSideProps(context) {
const userHandle = context.params.handle
return {
props: {
handle: userHandle
}
}
}
You don't need to list out the paths - any visit to /user/...
will run through that function. Also check out Next Dynamic Routes documentation to see how to handle catch-all routes and other parameters.
CodePudding user response:
You can handle dynamic routes by adding brackets to the file inside the pages folder.
for example you have a url of localhost:3000/ivanatias (ivanatias is your profile name)
on pages directory
pages/
[userProfileId].js
You can read more about Dynamic Routing
now context.params.userProfileId will get the parameters on your url which would be ivanatias
now you can perform a fetch query on the database inside getServerSideProps and get the data with userProfileId
export async function getServerSideProps(context) {
const userProfileId = context.params.userProfileId
const fakeFetch = await fetch(`someurl.com/profile/${userProfileId}`);
const data = await fakeFetch.json();
return {
props: {
data: data
}
}
}
now you can use the data on your component
for example
export default function profile({ data }) {
return (<h2>{data.name}</h2>)
}
now regarding your question if you're gonna use getStaticProps or getServerSideProps. it's up to you if you think that the data doesn't change much often then probably you can use ISG(Incremental Static Regeneration )