I’m trying to display comments from user posts using the JSONPlaceholder API.
Functionality:
Posts load from https://jsonplaceholder.typicode.com/posts and are displayed on the page.
The page displays the title and body properties from the post.
When a post’s body is clicked, the post’s comments are fetched from https://jsonplaceholder.typicode.com/posts/${postId}/comments.
The page displays the body property of all the comments for a post on the page after the post is clicked.
Posts have this structure:
{
“userId”: 1,
“id”: 1,
“title”: “sundent occaecati excepturi optio reprehenderit”,
“body”: “quia et recusandae consequuntur expedita et cumnreprehenderit molestiae ut ut quas totamnnostrum rerum est autem sunt rem eveniet architecto”
},
The post should display the title and body
Each post has 5 comments
A post’s comments have the following structure:
{
“postId”: 1,
“id”: 4,
“name”: “alias odio sit”,
“email”: “[email protected]”,
“body”: “non et leniti ut occaecati”
}
A post’s comments should only show after the post body is clicked.
All information can be displayed on the same page
=================================================
my code in App.js
import React, { useEffect, useState } from "react";
import PostDetail from "./PostDetail";
function App() {
const [posts, setPosts] = useState([]);
useEffect(() => {
fetch("https://jsonplaceholder.typicode.com/posts?userId=1")
.then((response) => response.json())
.then(setPosts)
.catch((error) => {
console.log(error)
});
}, []);
const listPosts = posts.map(post => <li>{post.tittle}</li>);
return (
<div className="App">
<PostDetail
/>
</div>
);
}
export default App;
===========================================
code in postDetail.js
import React, { useEffect, useState } from "react";
function postDetail() {
const [posts, setPosts] = useState([]);
useEffect(() => {
fetch(`https://jsonplaceholder.typicode.com/posts/${postId}/comments`)
.then((response) => response.json())
.then(setPosts)
.catch((error) => {
console.log(error)
});
}, []);
const listPosts = posts.map(post => {posts.tittle});
return (
<div className="App">
<button type="button" onClick={() => setAllData({...allData, currentUser : user})}>
{user.name}
</button>
</div>
);
}
Screenshot of errors:
[1]: https://i.stack.imgur.com/9gss7.png