Hello, I'm fairly new to programming and currently tackling a challenging exercise that has me a bit stuck.
- Display 10 posts from the API in the browser - Working
- Show 3 related comments for each post - Working
The issue I'm facing is that when I click on a post from the feed, all other comments are being fetched and displayed below each respective post simultaneously. What I want to achieve is to only display the comment related to the clicked post and hide it when clicking on another post.
Additionally, I am looking to implement a "load more" button that appears every time a set of comments is displayed, allowing users to fetch the latest 10 comments when clicked.
Any advice or suggestions on maintaining clean and readable code would be greatly appreciated!
Thank you in advance;
:)
Check out the code snippet below:
import React from "react";
import axios from "axios";
const postsID = "/posts";
const commentsID = "/comments";
var postsURL = `https://jsonplaceholder.typicode.com${postsID}`;
var commentsURL = `https://jsonplaceholder.typicode.com${commentsID}`;
class Posts extends React.Component {
constructor(props) {
super(props);
this.state = {
posts: [],
comments: [],
expanded: false,
commentsToShow: 3
};
this.clicked = this.clicked.bind(this);
}
clicked() {
axios.get(commentsURL).then(res => {
console.log("comments:", res);
this.setState({ comments: res.data });
});
}
componentDidMount() {
axios.get(postsURL).then(res => {
console.log("posts:", res);
this.setState({ posts: res.data });
});
}
render() {
return (
<div className="container">
<div className="jumbotron-div col s12">
<ul className="collection">
{this.state.posts.slice(0, 10).map(post => (
<div>
<div key={post.id} onClick={this.clicked}>
<h5>User ID: {post.id}</h5>
<p>Post: {post.body}</p>
</div>
<div>
<ul className="collection">
{this.state.comments
.filter(comment => comment.postId === post.id)
.slice(0, 3)
.map(comment => (
<li key={comment.id}>
<p>Comment ID: {comment.postId}</p>
<p>Comment: {comment.body}</p>
</li>
))}
</ul>
</div>
</div>
))}
</ul>
</div>
</div>
);
}
}
export default Posts;