Skip to content
the poor coder

fetch data next.js

Poor Man
Published
Reading time
2 min read
On this page

How to Fetch Data in Next.js#

If you're building an application with Next.js, you'll likely need to fetch data from an external API or server. Fortunately, Next.js makes this process relatively easy with its built-in data fetching methods.

Server-Side Rendering with getServerSideProps()#

If you need to fetch data at runtime on the server, you can use the getServerSideProps() function. This function runs on the server every time a user requests the page, and it passes the fetched data as a prop to the page component.

Text
export async function getServerSideProps(context) {
  const res = await fetch('https://api.example.com/data')
  const data = await res.json()

  return {
    props: {
      data
    }
  }
}

In this example, we're fetching data from an external API and passing it as a prop called "data" to our page component. We use the fetch() method to retrieve the data and then call res.json() to parse the response as JSON.

Static Site Generation with getStaticProps()#

If you don't need to fetch data at runtime on every request, you can use the getStaticProps() function to fetch the data at build time and generate a static HTML file for the page.

Text
export async function getStaticProps() {
  const res = await fetch('https://api.example.com/data')
  const data = await res.json()

  return {
    props: {
      data
    }
  }
}

This example is similar to the previous one, but we're using getStaticProps() instead of getServerSideProps(). This means that the data will be fetched at build time and used to generate a static HTML file for the page. This can improve performance, especially for pages with a lot of traffic.

Client-Side Rendering with useEffect()#

If you need to fetch data on the client side, you can use the useEffect() hook to make an API request after the component mounts.

Text
import { useState, useEffect } from 'react'

function MyComponent() {
  const [data, setData] = useState([])

  useEffect(() => {
    async function fetchData() {
      const res = await fetch('https://api.example.com/data')
      const newData = await res.json()
      setData(newData)
    }

    fetchData()
  }, [])

  return (
    <div>
      {data.map(item => (
        <div key={item.id}>{item.name}</div>
      ))}
    </div>
  )
}

In this example, we're using useState() to create a state variable called "data", which we'll update with the fetched data. We then use useEffect() to fetch the data from the API and update the state variable. The empty array passed as the second argument to useEffect() ensures that the effect only runs once when the component mounts.

Conclusion#

Next.js provides several options for fetching data in your application, depending on your specific use case. Whether you need to fetch data at runtime on the server, at build time, or on the client side, Next.js has you covered.

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC