Home > Enterprise >  TypeError: Cannot read properties of undefined (reading 'title'), 500 (Internal Server Err
TypeError: Cannot read properties of undefined (reading 'title'), 500 (Internal Server Err

Time:04-27

this is next project and this file is a dynamic route win run this code without return <h1>{ product.title }</h1> is work and I get the result in console, but if add this <h1>{product.title }</h1> I get 500 error from the server, I don't know why can someone told how to fix that and thank you

import React from 'react'
import { useRouter } from 'next/router'
import data from '../../utils/data'
import Layout from '../../components/Layout'

function Product() {

  const router = useRouter();
  const  slug  = router.query.id;
  const product = data.find((a) => a.slug === slug);

  console.log( product ) // her is show result



  return (
    <div>
        <Layout>
            <h1>{ product.title }</h1> // but her I get 500error product.title is undefined
        </Layout>
    </div>
  )
}

export default Product

CodePudding user response:

You should first filter the data and then get the title with map in the data synchronized with the slug.

  import React from 'react'
    import { useRouter } from 'next/router'
    import data from '../../utils/data'
    import Layout from '../../components/Layout'
    
    function Product() {
    
      const router = useRouter();
      const  slug  = router.query.id;
    
      return (
        <div>
            <Layout>
               data.filter((a) => a.slug === slug).map((obj)=> {
                 return (
                   <h1>{ obj.title }</h1> 
                 )
                })
            </Layout>
        </div>
      )
    }
    
    export default Product

CodePudding user response:

const product = data.find((a) => a.slug === slug);
console.log(product) // => `undefined` 
// Why?
console.log({ 
  currentSlug: slug,
  allSlugs: data.map(item => item.slug),
  currentSlugInAllSlugs: data.map(item => item.slug).includes(slug) 
});

To avoid the error:

 {product && (<h1>{ product.title }</h1>)}

Now, whenever a product is not found in data with the current router.query.id as slug, <h1> won't render, so the error will not happen.

The error is self explanatory: you can't access any property of undefined (you tried to access its .title).

  • Related