Reputation: 1276
I'm working on a next.js project and I'm trying to get the list of gyms from getStaticProps like this:
import { MapContainer, TileLayer, Marker, Popup } from "react-leaflet";
import { useState } from "react";
import { server } from '../config';
export default function Map ({gyms}){
console.log("data = "+ JSON.stringify(gyms));
return (
<MapContainer>
<TileLayer url={`I deleted the url`} attribution='Nothing to see here' />
{gyms.map((gym, index) => {
return (
<Marker
key={index}
position={[gym.address1, gym.address2]}
draggable={true}
animate={true}
>
</Marker>
);
})}
</MapContainer>
);
}
export async function getStaticProps() {
const res = await fetch(`${server}/api/gyms`)
const response = await res.json()
const gyms = response.gyms
console.log("gyms list = "+ gyms);
if (!gyms) {
return {
notFound: true,
}
}
return {
props: {
gyms,
// Will be passed to the page component as props
},
};
}
As you can see I have one console.log in the getStaticProps, that returns nothing, and another console log in the component that returns "data = undefined"
The error that I get is: TypeError: Cannot read properties of undefined (reading 'map')
Upvotes: 1
Views: 70
Reputation: 11
The error you are getting is from the 'gyms' prop. Please make sure if you are using useEffect in the component where you are using Map, the array variable should be in the array. Since you are getting the array as undefined then this is the most possible problem. Just put it in the array like this:
useEffect(() => {
//Code goes here...
}, [gyms])
Upvotes: 1