I try to fetch data by url with react. Server gives to url the list of objects in String in json ( String jsonBooks = new Gson().toJson(books);
). I try to get this in react app and render. But it is error:
TypeError: Cannot read property 'map' of undefined
import React, { Component } from 'react';
import './App.css';
class App extends Component {
state = {
books: []
}
componentDidMount() {
fetch(`http://localhost:8080/app/bookshop/books`,
{'mode': 'no-cors'},
{
headers: {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'GET, POST, HEAD, OPTIONS, PUT, DELETE, PATCH',
'Access-Control-Allow-Headers': 'X-Requested-With,content-type',
'Access-Control-Allow-Credentials': true
}})
.then(res => {
const books = res.data;
// console.log(res.data);
this.setState({books});
});
}
// http://localhost:8080/app/bookshop/books
cd
render() {
return (
<div>
<h1>Books:</h1>
<table>
<tr>
<th>Name</th>
<th>Author</th>
<th>Izdat</th>
<th>Genre</th>
<th>Price</th>
<th>Amount</th>
</tr>
{this.state.books.map(book =>
<tr><th>{book.name}</th>
<th>{book.author}</th>
<th>{book.izdat}</th>
<th>{book.genre}</th>
<th>{book.price}</th>
<th>{book.amount}</th>
</tr>
)}
</table>
</div>
);
}
}
export default App;
That's function on server (java, jax-rs):
@GET
@Produces({MediaType.APPLICATION_JSON})
@Path("/books")
public String Books() {
BooksDao booksDao = new BooksDao();
ArrayList<Book> books = booksDao.getBooks();
String jsonBooks = new Gson().toJson(books);
return jsonBooks;
}
What i have to do for fix?