concept api in category nextjs

appears as: API, APIs, pi
Next.js in Action

This is an excerpt from Manning's book Next.js in Action.

When a page in our application is rendered, it makes a request to one or more API endpoints to fetch the data that it needs. When the data arrives, the state of our component is set which updates the component on the screen accordingly. Depending on how the user interacts with the page, our component might make another API call which results in another state update. For example, the user might perform some action that requires refreshed data from the API, or they might need to update the API resource that our component is displaying.

Listing 2.1: The index.js page, or the site root, of the api-routes example application.
import Person from '../components/Person'
import fetch from 'isomorphic-unfetch'
 
const Index = ({ people }) => (
  <ul>
    {people.map((p, i) => (
      <Person key={i} person={p} />
    ))}
  </ul>
)
 
Index.getInitialProps = async () => {
  const response = await fetch('http://localhost:3000/api/people')
  const people = await response.json()
 
  return { people }
}
 
export default Index