Home > database >  object inside of props (general props/javascript question)
object inside of props (general props/javascript question)

Time:11-24

Just a bit of confusion over this:

export async function getServerSideProps() {
// Get all homes
const homes = await prisma.home.findMany();
// Pass the data to the Home page
return {
props: {
homes: JSON.parse(JSON.stringify(homes)),
},
};
}

  export default function Home({ homes = [] }) {
  return (
  <div>
  <h1 className="text-xl font-medium text-gray-800">
  Top-rated places to stay
  </h1>
  <p className="he">
  Explore some of the best places in the world
  </p>
  <div className="mt-8">
  <div>{homes} </div>
  </div>
  </div>    
  );

It works but I would have assumed that to access homes , you have to do homes.homes because homes is an object or property inside of props the props are passed to the function as 'homes' so if the props are named 'homes' then shouldnt the actual homes array be a property of that? Hence homes.homes can someone please explain why its not the case? Thanks

CodePudding user response:

The first parameter for a functional component is the whole props object. This props object is the same one that is on the right side of props: in getServerSideProps.

It might be easier to visualize without the destructuring, and by declaring an extra variable for the props object in getServerSideProps. The below code is equivalent to your current code.

export async function getServerSideProps() {
    // Get all homes
    const homes = await prisma.home.findMany();
    // Pass the data to the Home page
    const props = { homes: JSON.parse(JSON.stringify(homes)) }
    return {
        props: props,
    };
}
export default function Home(props) {
  const homes = props.homes ?? [];
  // ...

Above the const props in getServerSideProps is the exact same object as the props argument in Home. It has one property, homes, which could be called "a prop". That property looks to be an array taken from JSON.parse.

  • Related