Promise example

nextjs

Here’s an example of using Promises to make an API call in a Next.js server-side function:

import fetch from 'isomorphic-unfetch'

export default function getData() {
  return new Promise((resolve, reject) => {
    fetch('https://my-api.com/endpoint')
      .then(response => response.json())
      .then(data => resolve(data))
      .catch(error => reject(error))
  })
}

You can then call this function in a page component like this:

import getData from '../lib/getData'

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

MyPage.getInitialProps = async function() {
  try {
    const data = await getData()
    return { data }
  } catch (error) {
    return { error }
  }
}

If the getData function resolves with the data from the API, it will be passed to the page component as a prop. If the function rejects with an error, it will be caught in the catch block and you can handle the error as needed.