Proyectos de Subversion LeadersLinked - SPA

Rev

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

import { useEffect, useState } from 'react';
import { useDispatch } from 'react-redux';

import { addExperience, deleteExperience, editExperience } from '@services/profile/profiles';
import { addNotification } from '@store/notification/notification.actions';

export function useExperiences({ defaultExperiences = [] }) {
  const [experiences, setExperiences] = useState(defaultExperiences);
  const [modalState, setModalState] = useState(null);
  const [currentExperience, setCurrentExperience] = useState(null);
  const dispatch = useDispatch();

  const showModal = (type, experience = null) => {
    setCurrentExperience(experience);
    setModalState(modalState === type ? null : type);
  };

  const onAdd = async (uuid, experience) => {
    try {
      const newExperiences = await addExperience(uuid, experience);
      setExperiences(newExperiences);
      showModal(null);
    } catch (error) {
      dispatch(
        addNotification({
          style: 'danger',
          msg: `Error al agregar la experiencia: ${error.message}`
        })
      );
    }
  };

  const onEdit = async (experience) => {
    try {
      if (!currentExperience?.link_edit) {
        throw new Error('Enlace de edición no disponible');
      }
      const newExperiences = await editExperience(currentExperience.link_edit, experience);
      setExperiences(newExperiences);
      showModal(null);
    } catch (error) {
      dispatch(addNotification({ style: 'danger', msg: error.message }));
    }
  };

  const onDelete = async () => {
    try {
      if (!currentExperience?.link_delete) {
        throw new Error('Enlace de eliminación no disponible');
      }
      const newExperiences = await deleteExperience(currentExperience.link_delete);
      setExperiences(newExperiences);
      showModal(null);
    } catch (error) {
      dispatch(
        addNotification({
          style: 'danger',
          msg: `Error al eliminar la experiencia: ${error.message}`
        })
      );
    }
  };

  useEffect(() => {
    setExperiences(defaultExperiences);
  }, [defaultExperiences]);

  return {
    showModal,
    modalState,
    onAdd,
    onEdit,
    onDelete,
    experiences,
    currentExperience
  };
}