Rev 3665 | Ir a la última revisión | Autoría | Comparar con el anterior | Ultima modificación | Ver Log |
import { useEffect, useState } from 'react';
import { useDispatch } from 'react-redux';
import { useFetch } from '@hooks';
import { addComment, deleteComment } from '../services';
import { addNotification } from '@store/notification/notification.actions';
export function useKnowledge(uuid) {
const [comments, setComments] = useState([]);
const [knowledge, setKnowledge] = useState({
category: '',
title: '',
description: '',
link: null,
image: '',
attachment: '',
reaction: '',
routeComments: '',
routeCommentAdd: '',
routeSaveReaction: '',
routeDeleteReaction: ''
});
const dispatch = useDispatch();
const { data: knowledgeData, isLoading: knowledgeLoading } = useFetch(
uuid ? `/knowledge-area/view/${uuid}` : ''
);
const { data: commentsData, isLoading: commentsLoading } = useFetch(knowledge.routeComments);
const handleAddComment = async (comment) => {
try {
const newComment = await addComment(knowledge.routeCommentAdd, comment);
setComments((prevMessages) => [...prevMessages, newComment]);
} catch (error) {
dispatch(addNotification({ style: 'danger', msg: error.message }));
}
};
const handleDeleteComment = async (id, url) => {
try {
const message = await deleteComment(url);
const newComments = comments.filter((comment) => comment.unique !== id);
setComments(newComments);
dispatch(addNotification({ style: 'success', msg: message }));
} catch (error) {
dispatch(addNotification({ style: 'danger', msg: error.message }));
}
};
useEffect(() => {
if (knowledgeData) setKnowledge(knowledgeData);
}, [knowledgeData]);
useEffect(() => {
if (commentsData) setComments(commentsData);
}, [commentsData]);
return {
knowledge,
comments,
knowledgeLoading,
commentsLoading,
addComment: handleAddComment,
deleteComment: handleDeleteComment
};
}