I have a small news website with thousands of articles. I’m using NextJS (version 14 with pages directory) on the frontend and Strapi on the backend. Each article has “views” field in Strapi, which is 0 by default. Then I increment it like that:
export const Article = ({ data }) => {
const [views, setViews] = useState()
useEffect(() => {
async function addViews() {
setViews("loading")
const article = await getArticle(data.id)
if (article) {
await updateArticle(data.id, article.views + 1)
setViews(article.views + 1)
}
}
addViews()
}, [data])
return <article>
<h1>{data.title}</h1>
{(views && views !== "loading") && <span>{views}</span>}
<div dangerouslySetInnerHTML={{ __html: data.content }} />
</article>
}
Everything works fine, but sometimes views counter of some articles just randomly starts from 0 again. I know the code is far from perfect, I’m actually very new in the coding. What should I look into to improve it?