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

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.

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

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

>Solution :

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