A few days ago, while working on my portfolio I decided to have a page that would showcase posts that I made on this site. It took me a whole day trying to get it working, as I was new to using API and how to integrate them to a website, it was quite a challenge for me.
Here's how I made it work. I'm using gridsome, a static site generator for Vue to build my website. Also, keep in mind that the API is still in the beta stage.
First, install axios into your project file
yarn add axios or npm i axios
In the gridsome.server.js file, we'll declare a variable called axios
const axios = require('axios')
In the same file, we'll then configure the datastore API that lets us insert data into the graphql data layer.
module.exports = function(api) {
api.loadSource(async (actions) => {
const collection = actions.addCollection("Post");
const { data } = await axios.get(
"https://dev.to/api/articles?username=chrissiemhrk"
);
}
});
};
To get your API link go to https://docs.dev.to/api/#operation/getArticles
Copy the link highlighted in red and change the name at the end from ben to your dev username.
This section is where you'll see the content you can showcase. Personally, I chose the ID, title, description, and canonical_url.
module.exports = function(api) {
api.loadSource(async (actions) => {
const collection = actions.addCollection("Post");
const { data } = await axios.get(
"https://dev.to/api/articles?username=chrissiemhrk"
);
for (const item of data) {
collection.addNode({
id: item.id,
title: item.title,
description: item.description,
canonical_url: item.canonical_url,
});
}
});
};
Once done, go to the page you want your blog posts to appear and write this code in the file. This will enable us to query the data in our vue component. The content in the node will change depending on what you chose in the gridsome.server.js file
<page-query>
query {
allPost {
edges {
node {
id
title
description
canonical_url
}
}
}
}
</page-query>
At the beginning of the page, you'll add in code similar to this one below that will structure your posts the way you want.
<template>
<layout>
<article
v-for="edge in $page.allPost.edges"
:key="edge.node.id"
>
<h1>{{ edge.node.title }}</h1>
<p>{{ edge.node.description }}</p>
<g-link :to="edge.node.canonical_url">Read more</g-link>
</article>
</layout>
</template>
That's it the only thing left is to customize/style your page.
Top comments (0)