Made My First Fetch Request Using Next.js
Tags: nextjs, fetch, devto
Published: 2021-01-27 02:32:02

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 <a href="https://nextjs.org/"> nextjs </a> from the ladybug podcast and been, <i>not so secretly</i>, obsessed ever since, here's proof of that:

{% twitter 1353804995137855489 %}

I could write a blog on why <a href="https://nextjs.org/"> nextjs </a> has become popular, but I recommend listening to the <a href="https://www.ladybug.dev/"> podcast episode </a> or reviewing some of the following blogs:

<a href="https://www.freecodecamp.org/news/why-you-should-learn-next-js-as-a-react-developer/"> Why You Should Learn Next.js as a React Developer - FreeCodeCamp </a> 

<a href="https://medium.com/better-programming/next-js-for-react-why-you-should-give-it-a-try-right-now-e3b1886e4f20"> Next.js for React: Why You Should Give It a Try Right Now By Louis Petrik </a> 

<a href="https://medium.com/frontend-digest/whats-the-difference-between-nextjs-and-create-react-app-11b55650a612"> What’s The Difference Between NextJS and Create-React-App? By Malcolm Laing </a>


I am almost done with the step-by-step guide for <a href="https://nextjs.org/"> nextjs </a> and recently finished the <a href="https://nextjs.org/learn/basics/data-fetching"> Pre-rendering and Data Fetching </a> section of the guide.

The <a href="https://nextjs.org/learn/basics/data-fetching"> Pre-rendering and Data Fetching </a> 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. 

<h2> Simple Fetch Request To Get Dev.to post using Next.js </h2>

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: <a href="https://docs.dev.to/api/#section/Authentication"> https://docs.dev.to/api/#section/Authentication </a>.

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}``

<h3> Understanding the Next.js Terminology </h3>

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 <a href="https://nextjs.org/docs/basic-features/pages#static-generation-recommended"> Static Generation with data </a>. According to the <a href="https://nextjs.org/docs/basic-features/pages#static-generation-recommended"> nextjs </a> documentation, <i> "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." </i>

The <a href="https://nextjs.org/docs/basic-features/pages#static-generation-recommended"> nextjs </a> documentation also mentions,<i> "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." </i>

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 <a href="https://nextjs.org/"> nextjs </a>. 


<h3> Rendering the posts onto the page </h3>

First I made the external API fetch request to dev.to to get the posts. <i> (If you are following along make sure to input your username where is says "myUsername")</i>  Then, I return the posts under props. The documentation of <a href="https://nextjs.org/"> nextjs </a> 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,
    },
  };
}
```

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))} </>;
}
```

<h3> My entire code looks like this </h3> 

```
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;

```

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:
{% soundcloud https://soundcloud.com/maxxwell69/lush %}