Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import React, { useState, useEffect } from 'react'
- import CommentForm from './CommentForm'
- import { url } from '../utils/urls'
- import { replyComment, getChildrenComments } from '../utils/api'
- import { formatDateTime } from '../utils/utils'
- import user from '../image/user.png'
- function Comments(props) {
- const {comment, setIsReply, isReply} = props
- const [comments, setComments] = useState([])
- const [replied, setReplied] = useState(false)
- const handleNewComment = async(commentData)=> {
- const body = {content:commentData}
- try {
- const data = await replyComment(`${url}/api/comments/${comment.id}/reply/`, body)
- if(!data.error){
- setReplied(true)
- }
- } catch (error) {
- console.log(error.message)
- }
- }
- useEffect(()=> {
- const repliedComments = async()=> {
- try {
- const data = await getChildrenComments(`${url}/api/comments/${comment.id}/replies/`)
- setComments(data)
- setReplied(false)
- } catch (error) {
- console.log(error.message)
- }
- }
- repliedComments()
- }, [replied])
- return (
- <div className="comment-container__comment">
- <div className='comment-container-user'>
- <img src={user} alt="" />
- <span>admin</span>
- </div>
- <div className='comment-container-content'>
- <small>{formatDateTime(comment.created)}</small>
- <p>{comment.content}</p>
- <button type='button' onClick={()=>setIsReply({id:comment.id})}>Reply</button>
- </div>
- {isReply.id == comment.id &&
- <CommentForm handleNewComment={handleNewComment} setIsReply={setIsReply} >
- <button type='button' className='cancel-comment-btn' onClick={()=>setIsReply({id:null})}>Cancel</button>
- </CommentForm>
- }
- {comments && comments.map((comment)=> {
- return (
- <Comments
- key={comment.id}
- comment={comment}
- isReply={isReply}
- setIsReply={setIsReply}
- />
- )
- })}
- </div>
- )
- }
- export default Comments
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement