Strapi basic example with nextjs error

System Information
  • Strapi Version: v4.10.1
  • Operating System: win 11
  • Database: sqlite
  • Node Version: v18.16.0
  • NPM Version: 9.5.1
  • Yarn Version: -

works fine:

fetch('http://localhost:1338/api/restaurants', {
  method: 'GET',
  headers: {
    'Content-Type': 'application/json',
  },
})
  .then(response => response.json())
  .then(data => console.log(data));

Shows an error “TypeError: Cannot read properties of undefined (reading ‘data’)”

const Main = ({ restaurants, error }) => {
  if (error) {
    return <div>An error occured: {error.message}</div>;
  }
  return (
    <ul>
      {restaurants.data.map(restaurant => (
        <li key={restaurant.id}>{restaurant.attributes.Name}</li>
      ))}
    </ul>
  );
};

Main.getInitialProps = async ctx => {
  try {
    // Parses the JSON returned by a network request
    const parseJSON = resp => (resp.json ? resp.json() : resp);
    // Checks if a network request came back fine, and throws an error if not
    const checkStatus = resp => {
      if (resp.status >= 200 && resp.status < 300) {
        return resp;
      }

      return parseJSON(resp).then(resp => {
        throw resp;
      });
    };

    const headers = {
      'Content-Type': 'application/json',
    };

    const restaurants = await fetch('http://localhost:1338/api/restaurants', {
      method: 'GET',
      headers,
    })
      .then(checkStatus)
      .then(parseJSON);

    return { restaurants };
  } catch (error) {
    return { error };
  }
};

export default Main;