DEV Community

Brittany
Brittany

Posted on

Made My First Fetch Request Using Next.js

It has been a while since I have written a blog post and I wanted to share something that I learned this week. I recently found out about nextjs from the ladybug podcast and been, not so secretly, obsessed ever since, here's proof of that:

I could write a blog on why nextjs has become popular, but I recommend listening to the podcast episode or reviewing some of the following blogs:

Why You Should Learn Next.js as a React Developer - FreeCodeCamp

Next.js for React: Why You Should Give It a Try Right Now By Louis Petrik

What’s The Difference Between NextJS and Create-React-App? By Malcolm Laing

I am almost done with the step-by-step guide for nextjs and recently finished the Pre-rendering and Data Fetching section of the guide.

The Pre-rendering and Data Fetching guide is very helpful and I was able to fetch data using the file system provided in the guide. But, I wanted more practice and decided to make a fetch request to Dev.to.

Simple Fetch Request To Get Dev.to post using Next.js

First off, you should know that Dev.to has an api that is in beta still. You can find the documentation on how to set it up here: https://docs.dev.to/api/#section/Authentication .

I was able to get all of my blogs by making a fetch request using the following url: https://dev.to/api/articles?username={YourUserName}

Understanding the Next.js Terminology

After reading the documentation, I realized that for my particular task required to fetch the list of blog posts from the Dev.to api and that could be accomplished with Static Generation with data . According to the nextjs documentation, "static Generation is the pre-rendering method that generates the HTML at build time. The pre-rendered HTML is then reused on each request. In order to fetch this data on pre-render, Next.js allows you to export an async function called getStaticProps from the same file. This function gets called at build time and lets you pass fetched data to the page's props on pre-render."

The nextjs documentation also mentions, "getStaticProps only runs on the server-side. It will never run on the client-side. It won’t even be included in the JS bundle for the browser. That means you can write code such as direct database queries without them being sent to browsers."

Based off this information I was able to make my first fetch request to an external api (dev.to) to fetch my blogs and render them onto the page using nextjs .

Rendering the posts onto the page

First I made the external API fetch request to dev.to to get the posts. (If you are following along make sure to input your username where is says "myUsername") Then, I return the posts under props. The documentation of nextjs states that by returning { props: posts }, the entire component will receive posts as a prop at build time.

export async function getStaticProps() {
  const res = await fetch(
    "https://dev.to/api/articles?username={myUsername}"
  );
  const posts = await res.json();
  return {
    props: {
      posts,
    },
  };
}
Enter fullscreen mode Exit fullscreen mode

Then, I have a two functions that help to map over and render the posts. If you recall, Static Generation is the pre-rendering method that generates the HTML at build time. The pre-rendered HTML is then reused on each request. This function gets called at build time on server-side. It won't be called on client-side, so you can even do direct database queries. getStaticProps() make it so that my dev.to posts will be populated at build time.

function renderPosts(blog) {
  return (
    <div className="blogCard">
      <div className="blogCardImage">
        <img src={blog.social_image} alt="Image" />
      </div>
      <div className="blogCardContent">
        <h3>{blog.title}</h3>
        <span>{blog.description}</span>
      </div>
      <a href={blog.url} target="_blank">
        {" "}
      </a>
    </div>
  );
}

function devPosts({ posts }) {
  return <>{posts.map((post) => renderPosts(post))} </>;
}
Enter fullscreen mode Exit fullscreen mode

My entire code looks like this

function renderPosts(blog) {
  return (
    <div className="blogCard">
      <div className="blogCardImage">
        <img src={blog.social_image} alt="Image" />
      </div>
      <div className="blogCardContent">
        <h3>{blog.title}</h3>
        <span>{blog.description}</span>
      </div>
      <a href={blog.url} target="_blank">
        {" "}
      </a>
    </div>
  );
}

function Blogs({ posts }) {
  return <>{posts.map((post) => renderPosts(post))} </>;
}

export async function getStaticProps() {
  const res = await fetch(
    "https://dev.to/api/articles?username={myUsername}"
  );
  const posts = await res.json();
  return {
    props: {
      posts,
    },
  };
}

export default devPosts;

Enter fullscreen mode Exit fullscreen mode

If you have any questions/ advice feel free to comment.

I hope to learn to set up user Authentication/Authorization next on nextjs (pun intended).

As always thanks for reading!

Sincerely,
Brittany

Song of the day:

Oldest comments (1)

Collapse
 
jvarness profile image
Jake Varness

Next.js and Gatsby are both really awesome. Next has a lot of great features for building dynamic content, and offers a lot of control over how you do it. Gatsby is really great for static sites. Definitely can’t go wrong with either.