-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathNewComment.jsx
76 lines (72 loc) · 1.93 KB
/
NewComment.jsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
import { useContext, useState } from "react";
import { postNewCommentForArticle } from "./apiFunctions";
import { UserContext } from "./contexts/UserContext";
const NewComment = ({ setComments, articleid, setCommentCount }) => {
const { user } = useContext(UserContext);
const [displayError, setDisplayError] = useState(false);
const [newCommentText, setNewCommentText] = useState("");
const postNewComment = (event) => {
setDisplayError(false);
event.preventDefault();
const newComment = {
votes: 0,
author: user.username,
body: newCommentText,
created_at: new Date(),
article_id: articleid,
};
setComments((currentComments) => [newComment, ...currentComments]);
setCommentCount((currentCount) => currentCount + 1);
setNewCommentText("");
postNewCommentForArticle(articleid, newComment)
.then((new_comment) => {
setComments((currentComments) => {
return currentComments.map((comment) => {
if (comment === newComment) {
comment.comment_id = new_comment.comment_id;
}
return comment;
});
});
})
.catch(() => {
setDisplayError(true);
setCommentCount((currentCount) => currentCount - 1);
setComments((currentComments) => {
return currentComments.filter(
(comment) => comment !== newComment
);
});
});
};
return (
<div>
<h3 id="commentsTitle">Post a new comment</h3>
{displayError && (
<p id="errorMessage">
An error occurred when posting your comment
</p>
)}
<form
id={displayError ? "errorBox" : "newCommentBox"}
onSubmit={postNewComment}
>
<textarea
id="newCommentText"
placeholder="new comment text..."
required={true}
value={newCommentText}
onChange={(event) => setNewCommentText(event.target.value)}
/>
<button
type="submit"
id="postNewCommentButton"
className="brandedButton"
>
Post
</button>
</form>
</div>
);
};
export default NewComment;