nextjs fetch api example


Here’s an example of using the fetch API in a Next.js page:

import { useState, useEffect } from 'react'

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

  useEffect(() => {
    async function fetchData() {
      const res = await fetch('/api/example')
      const json = await res.json()
  }, [])

  if (!data) {
    return <div>Loading...</div>

  return (
      { => (
        <div key={}>{}</div>

export default Example

This example fetches data from an API endpoint at /api/example when the component is mounted. The response is awaited and then the JSON data is saved to the data state variable using the setData function. The component renders a loading message until the data is available, at which point it renders a list of items.