I have a common error when trying to pass data from parent to child component in next.js/react:
TypeError: Cannot read properties of undefined (reading 'screenName')
I believe that the error is being caused by the data not passing through but I am not able to see why. I have read next docs and my code is pretty textbook.
Here is the dynamic parent...
pages/artist/[artistId].js
import React from 'react'
import Head from 'next/head'
import ArtistHeader from '../../components/ArtistHeader'
import UploadButton from '../../components/UploadButton'
import styles from '../../styles/artistPage.module.css'
export default function Artist ({ artist }) {
return (
<section className={styles.wrapper}>
<Head>
<title>{artist.screenName}</title>
</Head>
<div className={styles.artistPage}>
<ArtistHeader data={artist}/>
<div className={styles.songContainer}>
<UploadButton />
</div>
</div>
</section>
)
}
export async function getStaticProps({ params }) {
const results = await fetch(`REDACTED API ENDPOINT`).then (r =>
r.json())
console.log(results)
return {
props: {
artist: results[0]
}
}
}
export async function getStaticPaths() {
const artists = await fetch('REDACTED API ENDPOINT').then (r =>
r.json())
return {
paths: artists.map(artist => {
return {
params: {
artistId: JSON.stringify(artist.userId)
}
}
}),
fallback: false
}
}
Here is the child component...
/components/ArtistHeader.js
import Image from 'next/image';
import styles from '../styles/artistPage.module.css'
export default function ArtistHeader({ artist }) {
return (
<header className={styles.artistContainer}>
<p>{artist.screenName}</p>
<Image
className={styles.artistHeader}
priority="true"
src={artist.artistMainImg}
alt={artist.screenName}
width="1280px"
height="200px"
layout="intrinsic"
objectPosition="center"
/>
</header>
)
}
This has to be something small but for the life of me I cannot see it.
Thanks in advance.
CodePudding user response:
I think you did a typo in props name:
// your code
<ArtistHeader data={artist}/>
// should be
<ArtistHeader artist={artist}/>
//as
function ArtistHeader({ artist }) {...}