Proyectos de Subversion LeadersLinked - SPA

Rev

Rev 3659 | Autoría | Comparar con el anterior | Ultima modificación | Ver Log |

import { useState } from 'react';

import { useAlert, useAlertModal, useApi } from '@shared/hooks';
import { addCapsuleComment, deleteCapsuleComment, getCapsule } from '@microlearning/services';

const DEFAULT_STATE = {
  uuid: '',
  name: '',
  description: '',
  image: '',
  link_comments: '',
  link_comment_add: '',
  link_slides: '',
  total_comments: '',
  total_rating: '0',
  progress: 0,
  completed: 0,
  total_slides: null,
  link_first_slide: '',
  type_first_slide: '',
  order: null,
  added_on: '',
  updated_on: ''
};

export function useCapsule(uuid) {
  const [capsule, setCapsule] = useState(DEFAULT_STATE);
  const [deletedUrl, setDeletedUrl] = useState(null);

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

  const { loading, execute: fetchCapsule } = useApi(getCapsule, {
    autoFetch: true,
    autoFetchArgs: [uuid],
    onSuccess: (data) => {
      setCapsule(data);
    },
    onError: (error) => {
      showError(error.message);
    }
  });

  const { execute: addComment } = useApi(addCapsuleComment, {
    onSuccess: ({ message, capsule: updatedCapsule, comment: newComment }) => {
      setCapsule((prev) => ({
        ...prev,
        ...updatedCapsule,
        comments: [newComment, ...prev.comments]
      }));
      showSuccess(message);
    },
    onError: (error) => {
      showError(error.message);
    }
  });

  const { execute: deleteComment } = useApi(deleteCapsuleComment, {
    onSuccess: ({ message, capsule: updatedCapsule }) => {
      setCapsule((prev) => ({
        ...prev,
        ...updatedCapsule,
        comments: prev.comments.filter((c) => c.link_delete !== deletedUrl)
      }));
      showSuccess(message);
      setDeletedUrl(null);
      closeAlert();
    },
    onError: (error) => {
      showError(error.message);
    }
  });

  const handleAddComment = (comment) => {
    addComment(capsule.link_comment_add, comment);
  };

  const removeComment = (url) => {
    setDeletedUrl(url);
    showAlert({
      message: '¿Estás seguro de querer eliminar este comentario?',
      onConfirm: () => deleteComment(url)
    });
  };

  return { capsule, loading, fetchCapsule, addComment: handleAddComment, removeComment };
}