I am trying to display the list of authors from my API, I've created simple component, and am using axios
. My API looks like this:
{
"links": [
{
"rel": "self",
"href": "http://localhost:8080/booker/api/authors"
}
],
"content": [
{
"authorId": 4,
"firstName": "Tonyslav",
"lastName": "Shamal",
"webPage": "www.tonisha.gov",
"dateCreated": "2021-12-15T11:58:28.829 00:00",
"numberOfBooks": 13,
"links": [
{
"rel": "books",
"href": "http://localhost:8080/booker/api/books/author/4"
}
]
},
{
"authorId": 6,
"firstName": "Georgio",
"lastName": "Martinez",
"webPage": "www.got.gov",
"dateCreated": "2021-12-15T11:58:28.829 00:00",
"numberOfBooks": 16,
"links": [
{
"rel": "books",
"href": "http://localhost:8080/booker/api/books/author/6"
}
]
}
}
And my React components looks like this:
import { useEffect, useState } from 'react';
import axios from 'axios';
const Authors = () => {
const [authors, setAuthors] = useState([]);
useEffect(() => {
axios.get('http://localhost:8080/booker/api/authors')
.then(res => {
setAuthors(res.data);
})
.catch(err => console.log(err));
}, []);
return (
<div>
{authors.map(author => (
<div className="card" key={author.content.authorId}>
{author.content.firstName}
</div>
))}
</div>
);
}
export default Authors;
This is my error from the console
TypeError: authors.map is not a function
Can anybody try to help me with this, i can not solve this error.
CodePudding user response:
The response is an object, not an array, so you can't map over it. You probably want something closer to this:
.then(res => {
setAuthors(res.data.content);
})
Assuming you want to loop over that array. Then the rendering would look something like this:
<div>
{authors.map(author => (
<div className="card" key={author.authorId}>
{author.firstName}
</div>
))}
</div>