| 3719 |
stevensc |
1 |
import { useEffect, useState } from 'react';
|
|
|
2 |
import { useDispatch } from 'react-redux';
|
|
|
3 |
|
|
|
4 |
import { axios } from '@app/utils';
|
|
|
5 |
import { useFetch } from '@hooks';
|
|
|
6 |
import { addNotification } from '@app/redux/notification/notification.actions';
|
|
|
7 |
|
|
|
8 |
export function usePosts(postUrl) {
|
|
|
9 |
const { data: post, isLoading, mutate } = useFetch(postUrl);
|
|
|
10 |
const [comments, setComments] = useState([]);
|
|
|
11 |
|
|
|
12 |
const dispatch = useDispatch();
|
|
|
13 |
|
|
|
14 |
const getComments = (url) => {
|
|
|
15 |
axios.get(url).then((response) => {
|
|
|
16 |
const { data, success } = response.data;
|
|
|
17 |
|
|
|
18 |
if (!success) {
|
|
|
19 |
const errorMessage = typeof data === 'string' ? data : 'Error interno. Intente más tarde.';
|
|
|
20 |
|
|
|
21 |
dispatch(addNotification({ style: 'danger', msg: errorMessage }));
|
|
|
22 |
return;
|
|
|
23 |
}
|
|
|
24 |
|
|
|
25 |
setComments(data);
|
|
|
26 |
});
|
|
|
27 |
};
|
|
|
28 |
|
|
|
29 |
const updateTotalShare = (value) => {
|
|
|
30 |
mutate((prevPost) => ({
|
|
|
31 |
...prevPost,
|
|
|
32 |
total_share_external: value
|
|
|
33 |
}));
|
|
|
34 |
};
|
|
|
35 |
|
|
|
36 |
const updateReactions = (reactions) => {
|
|
|
37 |
mutate((prevPost) => ({ ...prevPost, reactions }));
|
|
|
38 |
};
|
|
|
39 |
|
|
|
40 |
const updateMyReaction = (reaction) => {
|
|
|
41 |
mutate((prevPost) => ({ ...prevPost, my_reaction: reaction }));
|
|
|
42 |
};
|
|
|
43 |
|
|
|
44 |
const addComment = (comment) => {
|
|
|
45 |
const formData = new FormData();
|
|
|
46 |
formData.append('comment', comment);
|
|
|
47 |
|
|
|
48 |
axios
|
|
|
49 |
.post(post.comments_add_url, formData)
|
|
|
50 |
.then((response) => {
|
|
|
51 |
const { success, data } = response.data;
|
|
|
52 |
|
|
|
53 |
if (!success) {
|
|
|
54 |
const errorMessage =
|
|
|
55 |
typeof data === 'string' ? data : 'Error interno. Intente más tarde.';
|
|
|
56 |
throw new Error(errorMessage);
|
|
|
57 |
}
|
|
|
58 |
|
|
|
59 |
setComments((prevComments) => [...prevComments, data]);
|
|
|
60 |
})
|
|
|
61 |
.catch((error) => {
|
|
|
62 |
dispatch(addNotification({ style: 'danger', msg: error.message }));
|
|
|
63 |
});
|
|
|
64 |
};
|
|
|
65 |
|
|
|
66 |
useEffect(() => {
|
|
|
67 |
if (post.comments_url) getComments(post.comments_url);
|
|
|
68 |
}, [post]);
|
|
|
69 |
|
|
|
70 |
return {
|
|
|
71 |
post: { ...post, comments },
|
|
|
72 |
isLoading,
|
|
|
73 |
updateTotalShare,
|
|
|
74 |
addComment,
|
|
|
75 |
updateReactions,
|
|
|
76 |
updateMyReaction
|
|
|
77 |
};
|
|
|
78 |
}
|