Data sourcing with Astro and Contentful
This guide assumes you’re already using Contentful, but if you are looking to get started, the two links below are worth a look.
Assuming you have the Contentful client configured to fetch data, you will be able to query your entries using something similar to the code below. In my content model, the blog posts are of content type blogPost
.
The output of this query will look similar to the one below, but naturally yours may differ as our content models will likely be different.
The only field that really matters though is the tags field which is an array of strings.
You can see what the response of this query looks like in my demo site here: https://contentful-tags-data-viz.netlify.app/raw-tags/. And you can find the src
for this page in the repo here: src/pages/raw-tags.astro
Create time series data
To create a time series from a Contentful response, there’s a couple of things that need to happen.
createDefaultMonths
The first is to ensure that each tag has the complete set of months and years from the data set. Even if a tag wasn’t used in any given month of any given year, a count value of 0 will still need to be created. I’ve achieved this using the createDefaultMonths
function.
createTimeSeries
The createTimeSeries
function can now deal with grouping each tag, creating an object to hold the dates for each year and then incrementing the month counts if the tag has been used in any given month of the year.
The output of the function will produce a result similar to the below, with a new object being created for each tag and a full array of months for each year in the data set. My data set runs from 2019 to 2023.
You can see what the response of this function looks like in my demo site here: https://contentful-tags-data-viz.netlify.app/time-series/.
And you can find the src
for the complete function here: src/utils/create-time-series.js.
With the time series data in the correct shape, you can now move on to creating the chart.
Creating an SVG line chart
Creating charts is often something folks will use a library for, but I prefer the hand-cranked approach for two reasons.