-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPost.js
90 lines (76 loc) · 2.54 KB
/
Post.js
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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
import React, { useState, useEffect } from 'react';
import "./Post.css";
import Avatar from "@material-ui/core/Avatar";
import { db } from './firebase';
import firebase from 'firebase';
//import { Button } from '@material-ui/core';
function Post( {postId, user, username, caption, imageUrl} ) {
const [comments, SetComments] = useState([]);
const [comment, SetComment] = useState('');
useEffect(() => {
let unsubscribe;
if(postId){
unsubscribe = db
.collection("posts")
.doc(postId)
.collection("comments")
.orderBy("timestamp","desc")
.onSnapshot((snapshot) => {
SetComments(snapshot.docs.map(doc => doc.data()));
});
}
return () => {
unsubscribe();
};
}, [postId]);
const postComment = (event) => {
event.preventDefault();
db.collection("posts").doc(postId).collection("comments").add({
text: comment,
username: user.displayName,
timestamp: firebase.firestore.FieldValue.serverTimestamp()
});
SetComment('');
}
return (
<div className="post">
<div className="post__header">
<Avatar
className="post__avatar"
alt={username}
src="/static/images/avatar/1.jpg"
/>
<h3>{username}</h3>
</div>
<img className="post__image" alt={username} src={imageUrl} />
<h4 className="post__text"><strong>{username}</strong> {caption}</h4>
<div className="post__comments">
{comments.map((comment) => (
<p>
<strong>{comment.username}</strong> {comment.text}
</p>
))}
</div>
{user && (
<form className="post__commentBox">
<input
className="post__input"
type="text"
placeholder="Add a comment"
value={comment}
onChange={(e) => SetComment(e.target.value)}
/>
<button
className="post__button"
disabled={!comments}
type="submit"
onClick={postComment}
>
Post
</button>
</form>
)}
</div>
)
}
export default Post