Proyectos de Subversion LeadersLinked - SPA

Rev

Rev 2191 | Ir a la última revisión | | Ultima modificación | Ver Log |

Rev Autor Línea Nro. Línea
2190 stevensc 1
import { useEffect } from 'react'
2
import { useDispatch } from 'react-redux'
3
 
4
import { axios } from '@app/utils'
5
import { addNotification } from '@app/redux/notification/notification.actions'
6
import useFetch from './useFetch'
7
 
8
export default function usePosts(postUrl) {
9
  const { data: post, isLoading, mutate } = useFetch(postUrl)
10
 
11
  const dispatch = useDispatch()
12
 
13
  const getComments = (url) => {
14
    axios.get(url).then((response) => {
15
      const { data, success } = response.data
16
 
17
      if (!success) {
18
        const errorMessage =
19
          typeof data === 'string' ? data : 'Error interno. Intente más tarde.'
20
 
21
        dispatch(addNotification({ style: 'danger', msg: errorMessage }))
22
        return
23
      }
24
 
25
      mutate((prevPost) => ({ ...prevPost, comments: 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'
56
              ? data
57
              : 'Error interno. Intente más tarde.'
58
          throw new Error(errorMessage)
59
        }
60
 
61
        mutate((prevPost) => ({
62
          ...prevPost,
63
          comments: [...prevPost.comments, data]
64
        }))
65
      })
66
      .catch((error) => {
67
        dispatch(addNotification({ style: 'danger', msg: error.message }))
68
      })
69
  }
70
 
71
  useEffect(() => {
72
    if (post.comments_url) getComments(post.comments_url)
73
  }, [post])
74
 
75
  return {
76
    post,
77
    isLoading,
78
    updateTotalShare,
79
    addComment,
80
    updateReactions,
81
    updateMyReaction
82
  }
83
}