Reputation: 37
I'm setting up a NextJS app on my localhost machine and have followed along the great tutorial on the website, however when plugging in my local API I am having problems.
I'm getting an error when changing my JS code. The error is
TypeError: Cannot read property 'id' of undefined
(anonymous function)
/Users/mattcohen/hello-
next/.next/server/static/development/pages/index.js:1611:17
Here is my statement for the api:
Index.getInitialProps = async function() {
const res = await fetch('http://localhost:8888/api/mods')
const data = await res.json()
console.log(`Show data fetched. Count: ${data.length}`)
return {
mods: data.mods.map(entry => entry.show)
}
}
export default Index
And here is my page layout code
import Layout from '../components/MyLayout.js'
import Link from 'next/link'
import fetch from 'isomorphic-unfetch'
const Index = (props) => (
<Layout>
<h1>Batman TV Shows</h1>
<ul>
{props.mods.map(mod => (
<li key={mod.id}>
<Link as={`/p/${show.id}`} href={`/post?id=${mod.id}`}>
<a>{mod.brand_name}</a>
</Link>
</li>
))}
</ul>
Any ideas?
Upvotes: 1
Views: 3023
Reputation: 31703
I think you have a typo
...
<ul>
{props.mods.map(mod => (
<li key={mod.id}>
// here
<Link as={`/p/${show.id}`} href={`/post?id=${mod.id}`}>
<a>{mod.brand_name}</a>
</Link>
</li>
))}
</ul>
Shouldn't it be mod.id
instead of show.id
? There is no show
variable.
Or mayber it should be mod.show.id
?
Edit: Debugging it to know what is the error
First of all you can check what is comming from the props
.
const Index = (props) => (
<Layout>
<h1>Batman TV Shows</h1>
<p>{JSON.stringfy(props, null, 2)}</p>
<ul>
{props.mods.map(mod => (
<li key={mod.id}>
<Link as={`/p/${show.id}`} href={`/post?id=${mod.id}`}>
<a>{mod.brand_name}</a>
</Link>
</li>
))}
</ul>
)
This way you will see everything that is comming to your component. There you can see if the data you want to show mod.id
is there in the mods.map(mod => )
. But to be more specific, you can do
const Index = (props) => (
<Layout>
<h1>Batman TV Shows</h1>
<ul>
{props.mods.map((mod, i) => (
<li key={i}>
<p>{JSON.stringify(mod, null, 2)}</p>
</li>
))}
</ul>
)
This way you can see exactly what is inside mods
and see if there is the property id
.
There is some better ways of debugging this to know what is going on, but this way is a good an more visible one.
Upvotes: 2