Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

235
Visualizações
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

[API fetch result on right][1]

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

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>
      )
    }
    

Note that in the event the GET requests fails (i.e. the fetch returns a rejected Promise) or any other exception is thrown while processing the request/response, then you will want to guard this by using a try/catch. Either provide valid, defined prop values to the page, or return that an error occurred or that the page content was unable to be found.

export async function getStaticProps() {
  let blogs = [];
  try {
    const res = await fetch('https://ed-blog-api.herokuapp.com/api/posts');
    blogs = await res.json();
  } catch(error) {
    // handle error, logging, etc...
    // maybe optionally returning `notFound: true` as a 404
  }
  return {
    props: {
      blogs,
    },
  }
}
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda