use 'fs' writeFileSync in getStaticProps #14962
-
Hi everyone. I have built a Views Counter for my Blog Posts, which is working fine on my local machine. But when I push to master, it's not updating the Views Counter online. My relevant files:
Here is my code: // database.json - stores one object for each blog post
{
"data": [
{
"id": "first-next-js-blog-devdiary",
"views": 7,
"likes": 1
},
{
"id": "second-post",
"views": 4,
"likes": 1
}
]
} // db-utils.js - exports updateViews(id) that will be called in [id].js from getStaticProps
import fs from "fs";
import * as database from "../public/database.json";
export function updateViews(id) {
let dataArray = database.data;
const indexMatchingId = dataArray.findIndex((data) => {
if (data.id === id) {
return true;
}
});
if (dataArray[indexMatchingId].views) {
dataArray[indexMatchingId].views++;
const databaseJson = JSON.stringify(database.default);
const filePath = `${process.cwd()}/public/database.json`;
fs.writeFileSync(filePath, databaseJson);
} else {
console.log("Error!");
return "Update failed!";
}
} // [id].js - calls updateViews(params.id) inside getStaticProps
import Head from "next/head";
import { createElement, Fragment } from "react";
import { getAllPostIds, getPostData } from "../../lib/posts";
import marksy from "marksy";
import Prism from "../../public/prism/prism";
import { updateViews } from "../../lib/db-utils";
const compile = marksy({
createElement,
highlight(language, code) {
return Prism.highlight(code, Prism.languages.javascript, language);
},
});
export default function Post({ postData }) {
// Include Post Header here with Image and FrontMatter
return (
<Fragment>
<Head>
<title>{postData.title}</title>
<link href="/prism/prism.css" rel="stylesheet" />
</Head>
<div className="post">{compile(postData.content).tree}</div>
<style jsx>{`
.post {
width: 100%;
word-wrap: break-word;
}
`}</style>
</Fragment>
);
}
export async function getStaticPaths() {
const paths = getAllPostIds();
return {
paths,
fallback: false,
};
}
export async function getStaticProps({ params }) {
updateViews(params.id);
const postData = await getPostData(params.id);
return {
props: {
postData,
},
};
} I included all the code of the three files, if thats okay. The complete code is here: https://github.com/christiankozalla/nextjs-blog It's working in development on localhost:3000. When I navigate to a blog post, and navigate back to Home, the Card showing the post I clicked has its Views increased by one. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 4 replies
-
|
Beta Was this translation helpful? Give feedback.
getStaticProps
andgetStaticPaths
only run in build time to get statically rendered page. In dev mode, it keep rendering new static page to reflect the change in source code. In prod, it will never run as it already has static page to read from.