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>
))}
);
}
CodePudding user response:
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.