简体   繁体   中英

Not able to pass data from a page using getStaticProps to a child component

I'm working on a next.js project and I'm trying to pass data from "gymlist" page to "table" component.

this is the "gymlist" page where I have the getStaticProps function:

export default function Gyms({gyms}) {
   return (
       <Table gyms={gyms}/>
   )
}

export async function getStaticProps() {
  const res = await fetch(`${server}/api/gyms`)
  const gyms = await res.json()
  console.log(gyms);
  if (!gyms) {
    return {
      notFound: true,
    }
  }
  return {
    props: {
      gyms,
      // Will be passed to the page component as props
    },
  };
  
}

the console.log shows the list of the gyms that I have in the database correctly.

This is the table component where I get the error: gyms.map is not a function

export default function Table(props) {
   const [gyms, setGyms] = useState(props);

   return (
   {gyms?.map((gym, index) => (
      <p> {gym.name} </p>
   ))}
   );
}

As you try to use props.gyms to your useState default value, you are passing an object (the props object: { gyms: [...] } ), instead of the gyms array.

It could be solved by passing props.gyms to useState : useState(props.gyms) , or simply using props.gyms directly in your component render: {props.gyms.map(...)} .

You don't need state, in this case.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM