Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

205
Vistas
React not outputting axios catch errors on bad API call, getting JavaScript errors instead

When I make a bad request to my API that should not return anything, it crashes my app but doesn't console.log any of the error messages I set up for axios, instead I get a bunch of errors regarding the map I used in one of my components. I cannot seem to find the cause of the error.

The component with the map:

const Viewer=({poem})=>{
    return(
        <>
        {
            poem.map((item) => {
                let author = item.author
                let title = item.title
                let lines = item.lines
                if (author!= undefined && title!= undefined) {
                    return(
                        <>
                        <div className="viewer">
                            <div className="author">{author}</div>
                            <div className="title">{title}</div>
                            <div className="lines">
                                {lines.map((line) =>
                                    <div>{line}</div>
                                )}
                            </div>
                        </div> 
                        </>
                    )
                }
            })
        }
        </>
    )
}

Afterwards my page goes blank until I reload it and I get 3 error messages saying that poem.map is not a function.

Here is how I am fetching the API:

const searchPoem= (event) => {
    if(event.key==="Enter")
    {
      axios.get("https://poetrydb.org/"+option+"/"+search+"/all")
      .then(res=>setPoemData(res.data))
      .catch((err) => {
        if (err.response) {
          console.log(err.response.data)
          console.log(err.response.status)
          console.log(err.response.headers)
        } else if (err.request) {
          console.log(err.request)
        } else {
          console.log('Error', err.message)
        }
      })
    }
  }

The results get put into a div that generates a card using my viewer component

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

Try log the variable poem within the component.

If an API returns nothing, the variable poem will not exist in this context, and therefore neither will poem.map.

Have a look into conditional rendering - https://reactjs.org/docs/conditional-rendering.html

You could handle this in the rendering function with something similar to the below.

poem && Viewer(poem)
about 4 years ago · Juan Pablo Isaza Denunciar

0

When .map() is called on non-array variables, it will throws error.

Since the page breaks after a bad API call, one way to prevent it is to check if poem is an Array using Array.isArray() before performing poem.map().

const Viewer = ({ poem }) => {
  return (
    <>
      {Array.isArray(poem) // Add extra type checking before rendering
        ? (
          poem.map((item) => {
            let author = item.author;
            let title = item.title;
            let lines = item.lines;
            if (author != undefined && title != undefined) {
              return (
                <>
                  <div className="viewer">
                    <div className="author">{author}</div>
                    <div className="title">{title}</div>
                    <div className="lines">
                      {lines.map((line) => (
                        <div>{line}</div>
                      ))}
                    </div>
                  </div>
                </>
              );
            }
          })
        )
        : null // or a error message component
      }
    </>
  );
};
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda