0

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>
   ))}
   );
}

1 Answer 1

2

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.