Proyectos de Subversion LeadersLinked - SPA

Rev

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

Rev Autor Línea Nro. Línea
3629 stevensc 1
import React, { useEffect, useState } from 'react';
2
import { useParams } from 'react-router-dom';
3
 
4
import { useAlert, useAlertModal, useApi, useModal } from '@shared/hooks';
5
import {
6
  getConversations,
7
  deleteConversation as deleteConversationService
8
} from '@inmail/services';
9
import { SearchUserModal } from '@shared/components';
10
 
11
export function useConversations() {
12
  const { uuid } = useParams();
13
  const [conversations, setConversations] = useState([]);
14
  const [currentConversation, setCurrentConversation] = useState(null);
15
 
16
  const { showSuccess, showError } = useAlert();
17
  const { showAlert, closeAlert } = useAlertModal();
18
  const { showModal, closeModal } = useModal();
19
 
20
  const { loading, execute } = useApi(getConversations, {
21
    onSuccess: (data) => {
22
      setConversations(data);
23
    },
24
    onError: (error) => {
25
      showError(error.message);
26
    }
27
  });
28
 
29
  const { execute: executeDeleteConversation } = useApi(deleteConversationService, {
30
    onError: (error) => {
31
      showError(error.message);
32
    }
33
  });
34
 
35
  const handleDeleteConversation = async (url) => {
36
    executeDeleteConversation(url).then((data) => {
37
      showSuccess(data);
38
      setConversations((prev) => prev.filter((c) => c.deleted_url !== url));
39
      closeAlert();
40
    });
41
  };
42
 
43
  const deleteConversation = (url) => {
44
    showAlert({
45
      title: 'Borrar conversación',
46
      message: '¿Estás seguro de querer borrar esta conversación?',
47
      onConfirm: () => handleDeleteConversation(url),
48
      onCancel: closeAlert
49
    });
50
  };
51
 
52
  const startConversation = () => {
53
    showModal(
54
      'Iniciar conversación',
55
      <SearchUserModal
56
        onSelect={(user) => {
57
          setConversations((prev) => [user, ...prev]);
58
          setCurrentConversation(user);
59
          closeModal();
60
        }}
61
      />
62
    );
63
  };
64
 
65
  useEffect(() => {
66
    if (!uuid) return;
67
    const conversation = conversations.find((c) => c.uuid === uuid);
68
    setCurrentConversation(conversation);
69
  }, [uuid, conversations]);
70
 
71
  useEffect(() => {
72
    execute(uuid ? `/inmail/${uuid}` : '/inmail');
73
  }, [uuid]);
74
 
75
  return {
76
    conversations,
77
    loading,
78
    currentConversation,
79
    setCurrentConversation,
80
    deleteConversation,
81
    startConversation
82
  };
83
}