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