Skip to content

Commit f5c52f8

Browse files
committed
Implementing comments on a post
1 parent a1439a5 commit f5c52f8

File tree

1 file changed

+52
-1
lines changed

1 file changed

+52
-1
lines changed

src/components/screens/Home.js

Lines changed: 52 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -99,6 +99,39 @@ const Home = () => {
9999
});
100100
};
101101

102+
const makeAComment = (text, postId) => {
103+
fetch("/posts/comment", {
104+
method: "PUT",
105+
headers: {
106+
"Content-Type": "Application/json",
107+
Authorization: `Bearer ${localStorage.getItem("authorization")}`,
108+
"IMS-Request-Id": getUUIDV4().toString(),
109+
"IMS-Request-Date": new Date().toISOString(),
110+
},
111+
body: JSON.stringify({
112+
_id: postId,
113+
text,
114+
}),
115+
})
116+
.then((res) => {
117+
return res.json();
118+
})
119+
.then((result) => {
120+
console.log("COMMENT RESULT:", result);
121+
const newData = data.map((item) => {
122+
if (item._id === result.post._id) {
123+
return result.post;
124+
} else {
125+
return item;
126+
}
127+
});
128+
return setData(newData);
129+
})
130+
.catch((err) => {
131+
console.log("ERROR CATCH MAKE COMMENT HOME:", err);
132+
});
133+
};
134+
102135
return (
103136
<div className="home">
104137
{data.map((item) => {
@@ -137,7 +170,25 @@ const Home = () => {
137170
<h6>{item.likes.length} likes</h6>
138171
<h6>{item.title}</h6>
139172
<p>{item.body}</p>
140-
<input type="text" placeholder="add a comment" />
173+
{item.comments.map((record) => {
174+
return (
175+
<h6 key={record._id}>
176+
<span style={{ fontWeight: 500 }}>
177+
{record.postedBy.username}
178+
</span>
179+
&nbsp;{record.text}
180+
</h6>
181+
);
182+
})}
183+
184+
<form
185+
onSubmit={(e) => {
186+
e.preventDefault();
187+
makeAComment(e.target[0].value, item._id);
188+
}}
189+
>
190+
<input type="text" placeholder="add a comment" />
191+
</form>
141192
</div>
142193
</div>
143194
);

0 commit comments

Comments
 (0)