Next JS Fetch and Print Data From API Using getStaticProps() Method with Example

In this blog post, we see a simple example of fetching data from API and print in Component.

Script

First, create a getStaticProps() function to fetch data from API. The getStaticProps the method can be used inside a page to fetch data at build time.

export async function getStaticProps() {
  const res = await fetch("https://jsonplaceholder.typicode.com/posts?_limit=10")
  const data = await res.json()
  return {
    props: {
      data
    }
  }
}

After that print data.

export default function Home({data}) {
  return (
    <>
      <h1>Blog Page</h1> 
      <div>
        {data.map((post, i) => {
          return (
            <div key={i}>
              <h1>{post.title}</h1>
              <p>{post.body}</p>
          </div>
          )
        })}
      </div>
    </>
  )
}

Full code

index.js

export default function Home({data}) {
  return (
    <>
      <h1>Blog Page</h1> 
      <div>
        {data.map((post, i) => {
          return (
            <div key={i}>
              <h1>{post.title}</h1>
              {post.body}
          </div>
          )
        })}
      </div>
    </>
  )
}



export async function getStaticProps() {
  const res = await fetch("https://jsonplaceholder.typicode.com/posts?_limit=10")
  const data = await res.json()
  return {
    props: {
      data
    }
  }
}

Result

fetch data and print from API in nextjs
fetch data and print from API in next JS