Proyectos de Subversion LeadersLinked - SPA

Rev

Rev 3619 | Autoría | Ultima modificación | Ver Log |

import { useEffect, useState } from 'react';
import { useParams } from 'react-router-dom';

import { useAlert, useAlertModal, useApi } from '@shared/hooks';
import {
  getConversations,
  deleteConversation as deleteConversationService
} from '@inmail/services';

export function useConversations() {
  const { uuid } = useParams();
  const [conversations, setConversations] = useState([]);
  const [currentConversation, setCurrentConversation] = useState(null);

  const { showSuccess, showError } = useAlert();
  const { showAlert, closeAlert } = useAlertModal();

  const { loading, execute } = useApi(getConversations, {
    onSuccess: (data) => {
      setConversations(data);
    },
    onError: (error) => {
      showError(error.message);
    }
  });

  const handleDeleteConversation = async (url) => {
    try {
      const message = await deleteConversationService(url);
      showSuccess(message);
      setConversations((prev) => prev.filter((c) => c.uuid !== url));
    } catch (error) {
      showError(error.message);
    }
  };

  const deleteConversation = (url) => {
    showAlert({
      title: 'Borrar conversación',
      message: '¿Estás seguro de querer borrar esta conversación?',
      onConfirm: () => handleDeleteConversation(url),
      onCancel: closeAlert
    });
  };

  useEffect(() => {
    if (!uuid) return;
    const conversation = conversations.find((c) => c.uuid === uuid);
    setCurrentConversation(conversation);
  }, [uuid, conversations]);

  useEffect(() => {
    execute(uuid ? `/email/${uuid}` : '/email');
  }, [uuid]);

  return {
    conversations,
    loading,
    currentConversation,
    setCurrentConversation,
    deleteConversation
  };
}