fetch data next.js

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.

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.

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.

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.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe