Rev 3505 | AutorÃa | Ultima modificación | Ver Log |
import React, { useEffect, useState } from 'react';import { useDispatch } from 'react-redux';import { axios } from '@app/utils';import { showReportModal } from '@app/redux/report/report.actions';import { addNotification } from '@app/redux/notification/notification.actions';import CommentForm from './CommentForm';import CommentsList from './CommentList';import ConfirmModal from '@components/modals/ConfirmModal';export default function Comments({comments: defaultComments = [],onAdd = ({ totalComments, comment }) => {},addUrl = ''}) {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((c) => c.unique !== currentComment.unique));};const reportComment = (reportUrl) =>dispatch(showReportModal({reportUrl,type: 'Comentario',onComplete: () => removeComment()}));const deleteComment = async () => {axios.post(currentComment.link_delete).then((response) => {const { success, data } = response.data;if (!success) {throw new Error('Ha ocurrido un error al intentar eliminar el comentario.');}removeComment();setCurrentComment(null);setShowConfirm(false);dispatch(addNotification({ style: 'success', msg: data }));}).catch((error) => {dispatch(addNotification({ style: 'danger', msg: error.message }));});};const addComment = async (comment) => {try {const formData = new FormData();formData.append('comment', comment);const response = await axios.post(addUrl, formData);const { success, data: newComment, total_comments: totalComments } = response.data;if (!success) {throw new Error('Ha ocurrido un error al intentar agregar el comentario.');}setComments((prev) => [...prev, newComment]);onAdd({ comment: newComment, totalComments });} catch (error) {dispatch(addNotification({ style: 'danger', msg: error.message }));}};useEffect(() => setComments(defaultComments), [defaultComments]);return (<><CommentForm onSubmit={addComment} /><CommentsList comments={comments} onReport={reportComment} onDelete={handleDelete} /><ConfirmModalshow={showConfirm}onClose={() => setShowConfirm(false)}onAccept={deleteComment}/></>);}