I console.log the data and it display on console. But it didn't display the data on the browser. It's saying events.map is not a function

Viewed 67
import Layout from '@/components/Layout';
import { API_URL } from '@/config/index';

export default function HomePage({ events }) {

  return (
    <Layout>

      <h1>Upcoming Events</h1>

      {events.length === 0 && <h3>No events to show</h3>}

      {events.map((evt) => (
        <h3 key={evt.id}>{evt.name} </h3>
      ))}

    </Layout>
  );
}

export async function getStaticProps() {

  const res = await fetch(`${API_URL}/api/events`);

  const events = await res.json();

  return {
    props: { events },
    revalidate: 1,
  };
}
1 Answers

events can be undefined initially. That's the issue.

Define a default value for events

export default function HomePage({ events = [] }) { ...

and try using a ternary operator

{
    events.length === 0 ? (
        <h3>No events to show</h3>
    ) : (
        events.map(evt => <h3 key={evt.id}>{evt.name} </h3>)
    );
}

OR check whether the events is an array

     {events.length === 0 && <h3>No events to show</h3>}

      {Array.isArray(events) && events.map((evt) => (
        <h3 key={evt.id}>{evt.name} </h3>
      ))}
Related