Advertisement
shinhosuck1973

nested_comment.js

Apr 27th, 2024
622
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import React, { useState, useEffect } from 'react'
  2. import CommentForm from './CommentForm'
  3. import { url } from '../utils/urls'
  4. import { replyComment, getChildrenComments } from '../utils/api'
  5. import { formatDateTime } from '../utils/utils'
  6. import user from '../image/user.png'
  7.  
  8. function Comments(props) {
  9.   const {comment, setIsReply, isReply} = props
  10.   const [comments, setComments] = useState([])
  11.   const [replied, setReplied] = useState(false)
  12.  
  13.  
  14.   const handleNewComment = async(commentData)=> {
  15.     const body = {content:commentData}
  16.     try {
  17.       const data = await replyComment(`${url}/api/comments/${comment.id}/reply/`, body)
  18.       if(!data.error){
  19.         setReplied(true)
  20.       }
  21.     } catch (error) {
  22.       console.log(error.message)
  23.     }
  24.   }
  25.  
  26.   useEffect(()=> {
  27.     const repliedComments = async()=> {
  28.       try {
  29.         const data =  await getChildrenComments(`${url}/api/comments/${comment.id}/replies/`)
  30.         setComments(data)
  31.         setReplied(false)
  32.       } catch (error) {
  33.         console.log(error.message)
  34.       }
  35.     }
  36.     repliedComments()
  37.   }, [replied])
  38.  
  39.   return (
  40.     <div className="comment-container__comment">
  41.         <div className='comment-container-user'>
  42.           <img src={user} alt="" />
  43.           <span>admin</span>
  44.         </div>
  45.         <div className='comment-container-content'>
  46.           <small>{formatDateTime(comment.created)}</small>
  47.           <p>{comment.content}</p>
  48.           <button type='button' onClick={()=>setIsReply({id:comment.id})}>Reply</button>
  49.         </div>
  50.         {isReply.id == comment.id &&
  51.           <CommentForm handleNewComment={handleNewComment} setIsReply={setIsReply} >
  52.             <button type='button' className='cancel-comment-btn' onClick={()=>setIsReply({id:null})}>Cancel</button>
  53.           </CommentForm>
  54.          }
  55.         {comments && comments.map((comment)=> {
  56.           return (
  57.             <Comments
  58.               key={comment.id}
  59.               comment={comment}
  60.               isReply={isReply}
  61.               setIsReply={setIsReply}
  62.              />
  63.           )
  64.         })}
  65.     </div>
  66.    
  67.   )
  68. }
  69.  
  70. export default Comments
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement