1

I'm creating a page that will call my API route to return the value from my collection using MongoDB. But I'm having this error of Objects are not valid as a React child. I don't know why this happening. Can you please help me?

pages/index.js

export const getServerSideProps = async () => {
  const res = await fetch('http://localhost:3000/api/listings');
  const data = await res.json();

  if (!data) {
    return {
      notFound: true,
    };
  }

  return { props: { data } };
};

const index = async ({ data }) => {
  return (
    <>
      <section className='w-screen h-screen bg-hero-pattern bg-cover bg-no-repeat bg-bottom'></section>
      {data.map((prop) => (
        <div key={prop._id}>
          <h1>{prop.name}</h1>
          <h2 className='text-2xl truncate'>{prop.summary}</h2>
          <p>{prop.description}</p>
        </div>
      ))}
    </>
  );
};

pages/api/listings

import { connectToDatabase } from '../../middlewares/mongodb';

export const fetchDbData = async () => {
  const { db } = await connectToDatabase();
  const data = await db
    .collection('listingsAndReviews')
    .find({})
    .limit(1)
    .toArray();
  return JSON.parse(JSON.stringify(data));
};

export default async (req, res) => {
  const data = await fetchDbData();
  res.status(200).json(data);
};
Ahmet Emre Kilinc
  • 5,489
  • 12
  • 30
  • 42
rjc30
  • 227
  • 4
  • 14
  • What does `data` look like after you fetch it in `getServerSideProps`? – juliomalves May 08 '21 at 16:50
  • I'm not able to fetch the data because of the error. But the data is available when i tried to click the api route http://localhost:3000/api/listings – rjc30 May 09 '21 at 01:28
  • Import and call `fetchDbData` directly inside `getServerSideProps`. See [Internal API fetch with getServerSideProps? (Next.js)](https://stackoverflow.com/questions/65752932/internal-api-fetch-with-getserversideprops-next-js/65760948#65760948). – juliomalves May 09 '21 at 10:00

0 Answers0