3452 |
stevensc |
1 |
import { useEffect, useState } from 'react';
|
|
|
2 |
import { useDispatch } from 'react-redux';
|
|
|
3 |
|
|
|
4 |
import { useFetch } from '@hooks';
|
|
|
5 |
import { addComment, deleteComment } from '../services';
|
|
|
6 |
import { addNotification } from '@store/notification/notification.actions';
|
|
|
7 |
|
|
|
8 |
export function useKnowledge(uuid) {
|
|
|
9 |
const [comments, setComments] = useState([]);
|
|
|
10 |
const [knowledge, setKnowledge] = useState({
|
|
|
11 |
category: '',
|
|
|
12 |
title: '',
|
|
|
13 |
description: '',
|
|
|
14 |
link: null,
|
|
|
15 |
image: '',
|
|
|
16 |
attachment: '',
|
|
|
17 |
reaction: '',
|
|
|
18 |
routeComments: '',
|
|
|
19 |
routeCommentAdd: '',
|
|
|
20 |
routeSaveReaction: '',
|
|
|
21 |
routeDeleteReaction: ''
|
|
|
22 |
});
|
|
|
23 |
const dispatch = useDispatch();
|
|
|
24 |
|
|
|
25 |
const { data: knowledgeData, isLoading: knowledgeLoading } = useFetch(
|
|
|
26 |
uuid ? `/knowledge-area/view/${uuid}` : ''
|
|
|
27 |
);
|
|
|
28 |
const { data: commentsData, isLoading: commentsLoading } = useFetch(knowledge.routeComments);
|
|
|
29 |
|
|
|
30 |
const handleAddComment = async (comment) => {
|
|
|
31 |
try {
|
|
|
32 |
const newComment = await addComment(knowledge.routeCommentAdd, comment);
|
|
|
33 |
setComments((prevMessages) => [...prevMessages, newComment]);
|
|
|
34 |
} catch (error) {
|
|
|
35 |
dispatch(addNotification({ style: 'danger', msg: error.message }));
|
|
|
36 |
}
|
|
|
37 |
};
|
|
|
38 |
|
|
|
39 |
const handleDeleteComment = async (id, url) => {
|
|
|
40 |
try {
|
|
|
41 |
const message = await deleteComment(url);
|
|
|
42 |
const newComments = comments.filter((comment) => comment.unique !== id);
|
|
|
43 |
setComments(newComments);
|
|
|
44 |
|
|
|
45 |
dispatch(addNotification({ style: 'success', msg: message }));
|
|
|
46 |
} catch (error) {
|
|
|
47 |
dispatch(addNotification({ style: 'danger', msg: error.message }));
|
|
|
48 |
}
|
|
|
49 |
};
|
|
|
50 |
|
|
|
51 |
useEffect(() => {
|
|
|
52 |
if (knowledgeData) setKnowledge(knowledgeData);
|
|
|
53 |
}, [knowledgeData]);
|
|
|
54 |
|
|
|
55 |
useEffect(() => {
|
|
|
56 |
if (commentsData) setComments(commentsData);
|
|
|
57 |
}, [commentsData]);
|
|
|
58 |
|
|
|
59 |
return {
|
|
|
60 |
knowledge,
|
|
|
61 |
comments,
|
|
|
62 |
knowledgeLoading,
|
|
|
63 |
commentsLoading,
|
|
|
64 |
addComment: handleAddComment,
|
|
|
65 |
deleteComment: handleDeleteComment
|
|
|
66 |
};
|
|
|
67 |
}
|