Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

TypeError: cannot read property of undefined (reading 'map') while fetching from API

I am working on a full stack blog site project where I have created an API for back-end and its working fine and I am getting posts from it but when I try to iterate it using map it throws me error
Server Error TypeError: Cannot read properties of undefined (reading 'map'), I am using NextJS for my front-end.

Code

const Blogs = ({ blogs }) => {
  return (
    <div className='all-blogs'>
      {blogs.map((blog) => (
        <div className='single-blog' key={blog._id}>
          <h1>{blog.title}</h1>
          <p>{blog.text}</p>
        </div>
      ))}
    </div>
  )
}

export async function getStaticProps() {
  const res = await fetch(
    'https://ed-blog-api.herokuapp.com/api/posts'
  )
  const blogs = await res.json()

  return {
    props: {
      blogs,
    },
  }
}

endpoint I am fetching: https://ed-blog-api.herokuapp.com/api/posts

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[API fetch result on right][1]

>Solution :

The issue here is that blogs, as a prop value, is undefined until the asynchronous logic defines and populates it. You can handle this a couple ways.

  1. Provide a default prop value.

    const Blogs = ({ blogs = [] }) => {
      return (
        <div className='all-blogs'>
          {blogs.map((blog) => (
            <div className='single-blog' key={blog._id}>
              <h1>{blog.title}</h1>
              <p>{blog.text}</p>
            </div>
          ))}
        </div>
      )
    }
    
  2. Provide a fallback value to map from.

    const Blogs = ({ blogs }) => {
      return (
        <div className='all-blogs'>
          {(blogs ?? []).map((blog) => (
            <div className='single-blog' key={blog._id}>
              <h1>{blog.title}</h1>
              <p>{blog.text}</p>
            </div>
          ))}
        </div>
      )
    }
    
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading