Using the DEV API to add DEV.to comment counts to my blog
Currently my personal blog site doesn’t support comments. Since I cross-post all of my posts to DEV, I got the idea to show how many comments my blog post has received on DEV:
My blog is open-source, so you can check out the code over on Github.
Using DEV.to’s API
DEV provides an articles API that lets you get data about any article that has been published on DEV. Each article will look something like this:
The two values that I’m interested in from this API are the comments_count
and url
values.
Storing the article ID in my frontmatter
Each of my posts are written in Markdown, with a bunch of metadata known as the frontmatter at the top. The frontmatter for this post looks like this:
I’m storing the article ID in the frontmatter, so that when this post is rendered, I can call DEV’s API with that ID.
Finding your DEV article’s ID
I needed to add this devArticleId
value to all of my Markdown posts. I ended up doing this manually by grabbing a list of my articles on DEV using this endpoint:
And then cross-referencing the DEV articles with my blog posts.
Alternatively, if I wanted to grab the ID for a specific article I can also find that by inspecting the article’s source code on DEV and looking for data-article-id
:
Creating a data-fetching hook
Since my blog runs on Gatsby, I can create a React hook to fetch my data:
I’m returning two values here - loading
and data
. While loading
is true, I don’t render anything and wait for the data to load. Once the data comes in, I can display either the number of comments on my post, or a prompt to leave a comment.
After creating this component, I also took the time to install Jest and add some unit tests. Unit tests are definitely something I tend to neglect in my side projects, so I want to make a conscious effort to properly unit-test this blog!