Fetch Blog Articles from HashNode From a Specific User

PHOTO EMBED

Wed Mar 09 2022 21:19:03 GMT+0000 (Coordinated Universal Time)

Saved by @sarah__codes #javascript #api #hashnode #vanilla

/* 
HTML
<h1>
 Recent Ramblings
</h1>
<div id="articles">
</div>
*/

const fetchArticles = async (query, variables = {}) => {
  const data = await fetch("https://api.hashnode.com/", {
    method: "POST",
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({
      query,
      variables
    })
  });
  return data.json();
}

const articleQuery = `
query GetUserArticles($page: Int!) {
        user(username: "sarahcodes") {
            publication {
                posts(page: $page) {
                    title
                    brief
                    coverImage
                    slug
                }
            }
        }
    }
`;

fetchArticles(articleQuery, {
    page: 0
  })
  .then(result => {
    console.log(result.data.user)
    const articles = result.data.user.publication.posts;
    let container = document.createElement('div');
    container.classList.add("row");
    articles.forEach(article => {

      let link = document.createElement('a');
      link.href = `https://sarahdepalo.hashnode.dev/${article.slug}`;
      
      let articleContainer = document.createElement('div');
      articleContainer.classList.add("col")

      let title = document.createElement('h2');
      title.innerText = article.title;

      let image = document.createElement('img');
      image.src = article.coverImage;

      let brief = document.createElement('p');
      brief.innerText = article.brief;
			
      container.appendChild(link);
      link.appendChild(articleContainer);
      articleContainer.appendChild(title);
      articleContainer.appendChild(image);
      articleContainer.appendChild(brief);
    })
    document.querySelector('#articles').appendChild(container);
  })
content_copyCOPY

Referenced this great article: https://catalins.tech/hashnode-api-how-to-display-your-blog-articles-on-your-portfolio-page Hashnode playground: https://api.hashnode.com/