Rev 3697 | Autoría | Comparar con el anterior | Ultima modificación | Ver Log |
import React, { useEffect, useState } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { useForm } from 'react-hook-form';
import { axios } from '@utils';
import { addNotification } from '@store/notification/notification.actions';
import Modal from '@components/UI/modal/Modal';
import Input from '@components/UI/inputs/Input';
import Ckeditor from '@components/common/ckeditor/Ckeditor';
import TagsInput from '@components/UI/TagsInput';
import FormErrorFeedback from '@components/UI/form/FormErrorFeedback';
const QuestionModal = ({ show, url, isEdit, onClose, onComplete }) => {
const [questionsCategories, setQuestionsCategories] = useState([]);
const [currentCategories, setCurrentCategories] = useState([]);
const labels = useSelector(({ intl }) => intl.labels);
const dispatch = useDispatch();
const {
register,
control,
handleSubmit,
setValue,
formState: { errors }
} = useForm();
const onSubmit = handleSubmit(({ category_id, ...data }) => {
const formData = new FormData();
category_id.map((value) => formData.append('category_id[]', value));
Object.entries(data).map(([key, value]) => formData.append(key, value));
axios.post(url, formData).then((response) => {
const { data, success } = response.data;
if (!success) {
const errorMessage =
typeof data === 'string'
? data
: 'Error interno. Por favor, inténtelo de nuevo más tarde.';
dispatch(addNotification({ style: 'danger', msg: errorMessage }));
return;
}
onComplete();
onClose();
});
});
const getCategories = () => {
axios
.get('/my-coach')
.then((response) => {
const { data, success } = response.data;
if (!success) {
const errorMessage =
typeof data === 'string'
? data
: 'Error interno. Por favor, inténtelo de nuevo más tarde.';
dispatch(addNotification({ style: 'danger', msg: errorMessage }));
return;
}
const categories = Object.entries(data.categories).map((values) => ({
label: values[1],
value: values[0]
}));
setQuestionsCategories(categories);
})
.catch((err) => {
dispatch(addNotification({ style: 'danger', msg: err.message }));
});
};
const onTagsChange = (tags) => {
const categories = tags.map((tag) => tag.value);
setValue('category_id', categories);
};
useEffect(() => {
getCategories();
register('description', { required: 'Este campo es requerido.' });
register('category_id', {
required: 'Este campo es requerido.',
validate: (val) => val.length > 0 || 'Por favor, seleccione una categoria.'
});
}, []);
useEffect(() => {
if (!url || !show || !isEdit || !questionsCategories.length) return;
axios.get(url).then((response) => {
const { data, success } = response.data;
if (!success) {
const errorMessage =
typeof data === 'string'
? data
: 'Error interno. Por favor, inténtelo de nuevo más tarde.';
dispatch(
addNotification({
style: 'danger',
msg: errorMessage
})
);
return;
}
const categories = data.category_id.map((uuid) =>
questionsCategories.find((c) => c.value === uuid)
);
setCurrentCategories(categories);
setValue('title', data.title);
setValue('description', data.description);
});
}, [url, show, isEdit, questionsCategories]);
useEffect(() => {
if (!show) {
setCurrentCategories([]);
setValue('category_id', []);
setValue('description', '');
setValue('title', '');
}
}, [show]);
return (
<Modal
title={`${isEdit ? labels.edit : labels.add} ${labels.question}`}
show={show}
onClose={onClose}
onAccept={onSubmit}
>
<Input
name='title'
control={control}
rules={{ required: labels.error_field_empty }}
error={errors.title?.message}
/>
<TagsInput
label='Categorías'
name='category_id'
onChange={onTagsChange}
suggestions={questionsCategories}
defaultValue={currentCategories}
/>
{errors.category_id && <FormErrorFeedback>{errors.category_id?.message}</FormErrorFeedback>}
<Ckeditor
name='description'
control={control}
rules={{ required: labels.error_field_empty }}
error={errors.description?.message}
/>
</Modal>
);
};
export default QuestionModal;