Proyectos de Subversion LeadersLinked - SPA

Rev

Rev 3538 | Rev 3545 | Ir a la última revisión | Autoría | Comparar con el anterior | Ultima modificación | Ver Log |

import { useEffect, useState } from 'react';

import { useAlert, useAlertModal, useFetch } from '@shared/hooks';
import { addCapsuleComment, deleteCapsuleComment } 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 { showSuccess, showError } = useAlert();
  const { showAlert } = useAlertModal();

  const { data, loading, refetch } = useFetch(`/microlearning/capsules/${uuid}`);

  const addComment = async ({ comment, rating }) => {
    try {
      const {
        message,
        capsule,
        comment: newComment
      } = await addCapsuleComment(capsule.link_comment_add, {
        comment,
        rating
      });
      showSuccess(message);
      setCapsule((prev) => ({ ...prev, ...capsule, comments: [newComment, ...prev.comments] }));
    } catch (error) {
      showError(error.message);
    }
  };

  const removeComment = async (url, uuid) => {
    try {
      const { message, capsule } = await deleteCapsuleComment(url);
      showSuccess(message);
      setCapsule((prev) => ({
        ...prev,
        ...capsule,
        comments: prev.comments.filter((c) => c.uuid !== uuid)
      }));
    } catch (error) {
      showError(error.message);
    }
  };

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

  useEffect(() => {
    if (data) setCapsule(data);
  }, [data]);

  return { capsule, loading, refetch, addComment, deleteComment };
}