So, recently I have been dealing with making a blog website where the user can both read everything I want to tell them in the text and leave a comment so that I can know their opinion. I use markdown files to make the blog like that:
export async function getStaticProps({ params: { postname } }) {
const fileName = readFileSync(`posts/${postname}.md`, 'utf-8')
const { data: frontmatter, content } = matter(fileName)
const snapshot = await retrieveComments(postname).then(snapshot => {
return { props: { snapshot } }
})
const slug = postname
return {
props: {
frontmatter,
content,
snapshot,
slug
}
}
}
Before that I get the paths:
export async function getStaticPaths() {
const files = readdirSync('posts')
const paths = files.map(fileName => ({
params: {
postname: fileName.replace('.md', '')
}
}))
return {
paths,
fallback: false
}
}
Well, as you can see, I retrieve the markdown data, work with it and get the snapshot of the list of the comments in the database in getStaticProps
.
The problem is that the list of comments never changes its value in the production version, which happens because I get the static props. So I have found out that I can revalidate the props. How do I send the request that the props need to be revalidated when a new comment is added? Obviously, adding a new comment means changing the database, so I think we can sort of wait for a change in the database.
In api/revalidate.js
I have this:
export default async function handler(req, res) {
try {
await res.revalidate(req.query.path);
return res.json({
revalidated: true
})
} catch (err) {
return res.status(500).send('Error revalidating');
}
}
Also, I use Vercel as my hosting.