Mladen Milosavljevic
Mladen Milosavljevic

Reputation: 1810

Next.js Compile error, property undefined

So there is a indexpage with components, listing ads.

const App = ({ads}) => (
  { (ads.items===undefined) ? <></> :  ads.items.map(item => <Ad item={item} key={item.postingId} id={item.postingId}/>) }
)





export async function getServerSideProps(context) {
const res = await fetch(`www.apiadress.com/${queryString.stringify(context.query)}`)
const ads = await res.json()
// console.debug(ads)
console.debug(queryString.stringify(context.query))
return {
  props: {ads}, // will be passed to the page component as props
}
}

and component Ad receives those props, and renders cards

const Ad = props => (

    <Card className="customCard">
        <Card.Body>
            <Card.Text className="text">          
                <div className="mainDetails">
                <h1 className="ad_Title"><Link href="[ad]" as={props.item.postingId}>{props.item.title}</Link></h1>
                    <p>posted on: {props.item.postingDate.day} / {props.item.postingDate.month}
                    {props.item.postingDate.year}   by {props.item.employer} 
                    </p>

             
                    
                    <div className="description">
                        <p><span><Cash /><b> {props.item.rateFrom}- {props.item.rateTo}  per hour </b></span>     <GeoAlt /> <b>{props.item.city}</b></p>
                        <p> <Clock />  <b>{props.item.jobType}</b></p>  
                    </div>    
                   
                    <p>{props.item.description.slice(0, 230)}.....</p>
                   
                </div>            
          

                <div>
                    <img src={props.item.employerLogoUrl} alt={props.item.employer} className="empImg" />
                    <Button variant="primary" href=""> <Heart width="12" height="12"/>  SHORLIST  </Button>
                </div>

            </Card.Text>

        </Card.Body>
    </Card>



export default Ad;

with NPM run dev - everything works perfectly but at NPM run build I am getting an error

Error occurred prerendering page "/componenets/ad/ad". Read more: https://err.sh/next.js/prerender-error TypeError: Cannot read property 'postingId' of undefined

  1. What's causing this? I am assuming that components does not have data before render.
  2. How to solve this problem?

Upvotes: 3

Views: 1736

Answers (2)

duc mai
duc mai

Reputation: 1422

it simply that you have some items in your array null so it caused that error. I suggest to rewrite like this so it can avoid unnecessary error

const App = ({ads}) => 
   (ads.items || []).map(item => item ? <Ad item={item} key={item.postingId} id={item.postingId}/> : null)

Upvotes: 2

Or Assayag
Or Assayag

Reputation: 6336

  1. props.item is empty on cards component.
  2. Add validation check in the start of the Ad component:
    if (!props.item) {
        return null;
    }

Upvotes: 1

Related Questions