Rev 2521 | Rev 2868 | Ir a la última revisión | 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 { Form } from 'react-bootstrap'
import { Box } from '@mui/material'
import { axios } from 'utils/index'
import { addNotification } from '../../redux/notification/notification.actions'
import CKEditor from '@app/components/UI/Ckeditor'
import Modal from 'components/UI/modal/Modal'
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,
handleSubmit,
setValue,
watch,
formState: { errors }
} = useForm()
const watchedDescription = watch('description')
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) => ({
name: 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}
>
<Form.Group>
<Form.Label>{labels.title}</Form.Label>
<Form.Control
type='text'
name='title'
ref={register({ required: true })}
/>
{errors.title && (
<FormErrorFeedback>{labels.error_field_empty}</FormErrorFeedback>
)}
</Form.Group>
<Box mt={2}>
<label>Categorías</label>
<TagsInput
suggestions={questionsCategories}
settedTags={currentCategories}
onChange={onTagsChange}
/>
{errors.category_id && (
<FormErrorFeedback>{errors.category_id?.message}</FormErrorFeedback>
)}
</Box>
<CKEditor
defaultValue={watchedDescription}
onChange={(value) => setValue('description', value)}
/>
{errors.description && (
<FormErrorFeedback>{labels.error_field_empty}</FormErrorFeedback>
)}
</Modal>
)
}
export default QuestionModal