Proyectos de Subversion LeadersLinked - SPA

Rev

Rev 2844 | Rev 2846 | Ir a la última revisión | Autoría | Comparar con el anterior | Ultima modificación | Ver Log |

import React, { useEffect, useState } from 'react'
import { useDispatch } from 'react-redux'

import { axios } from '@app/utils'
import { addNotification } from '@app/redux/notification/notification.actions'
import { showReportModal } from '@app/redux/report/report.actions'

import CommentItem from './comment-item'
import ConfirmModal from '@app/components/modals/ConfirmModal'
import EmptySection from '@components/UI/EmptySection'

export default function CommentsList({ comments: defaultComments = [] }) {
  const [comments, setComments] = useState(defaultComments)
  const [currentComment, setCurrentComment] = useState(null)
  const [showConfirm, setShowConfirm] = useState(false)
  const dispatch = useDispatch()

  const handleDelete = (comment) => {
    setCurrentComment(comment)
    setShowConfirm(true)
  }

  const removeComment = () => {
    setComments((prev) =>
      prev.filter((comment) => comment.unique !== currentComment.unique)
    )
  }

  const onCloseConfirm = () => {
    setShowConfirm(false)
    setCurrentComment(null)
  }

  const reportComment = (reportUrl) =>
    dispatch(
      showReportModal({
        reportUrl,
        type: 'Comentario',
        onComplete: () => removeComment()
      })
    )

  const deleteComment = () => {
    axios
      .post(currentComment.link_delete)
      .then((response) => {
        const { success, data } = response.data

        if (!success) {
          throw new Error(
            'Error al eliminar un comentario, por favor intente más tarde'
          )
        }

        dispatch(addNotification({ style: 'success', msg: data }))
        removeComment()
        onCloseConfirm()
      })
      .catch((error) => {
        dispatch(addNotification({ style: 'danger', msg: error.message }))
      })
  }

  useEffect(() => setComments(defaultComments), [defaultComments])

  if (!comments.length) {
    return <EmptySection message='No hay comentarios' />
  }

  return (
    <>
      {comments.map((comment) => (
        <CommentItem
          key={comment.unique}
          comment={comment}
          onDelete={handleDelete}
          onReport={reportComment}
        />
      ))}
      <ConfirmModal
        show={showConfirm}
        onClose={onCloseConfirm}
        onAccept={deleteComment}
      />
    </>
  )
}