I have an issue rendering this code in the browser, is there a way I can fix this? If there's more information needed, let me know? I receive the error at the componentDidMount. Is there something I am doing wrong.
The PostService is posted at the bottom.
import React, { Component } from 'react';
import PostService from '../services/PostService';
class ListPost extends Component {
constructor(props) {
super(props);
this.state = {
posts: []
};
}
componentDidMount(){
PostService.getPosts().then((response) => {
this.setState({ posts: response.data });
});
}
render() {
return (
<div>
<h2 className="text-center">Posts</h2>
<div className="row">
<table className="table table--striped table-boarded">
<thead>
<tr>
<th>Title</th>
<th>Description</th>
<th>Content</th>
</tr>
</thead>
<tbody>
{
this.state.posts.map(
post =>
<tr key={post?.id}>
<td>{post?.description}</td>
<td>{post?.title}</td>
<td>{post?.content}</td>
</tr>
)}
</tbody>
</table>
</div>
</div>
)
}
}
export default ListPost;
import axios from "axios";
const POST_API_BASE_URL = "http://localhost:8080/api/posts";
class PostService {
getPosts() {
axios.get(POST_API_BASE_URL);
}
}
export default new PostService();
First of all change your PostService to;
import axios from "axios";
const POST_API_BASE_URL = "http://localhost:8080/api/posts";
export default function getPosts() {
return axios.get(POST_API_BASE_URL);
}
And import as import getPosts from '../services/PostService'; on your ListPost class.
Then use the code below. You shouldn't be setting state inside componentDidMount
componentDidMount() {
this.getData();
}
getData = () => {
getPosts()
.then(response => {
this.setState({ posts: response.data });
})
.catch(error => {
// handle errors here
})
}