Autoría | Ultima modificación | Ver Log |
import React, { useEffect, useState } from 'react'
import { useForm } from 'react-hook-form'
import { CKEditor } from 'ckeditor4-react'
import { useDispatch, useSelector } from 'react-redux'
import { Button, Form, Modal } from 'react-bootstrap'
import { CKEDITOR_OPTIONS, axios } from '../../utils'
import { addNotification } from '../../redux/notification/notification.actions'
import Spinner from '../UI/Spinner'
import FormErrorFeedback from '../UI/FormErrorFeedback'
const AnswerModal = ({
show = false,
currentAnswer = '',
url = '',
onClose = () => null,
onComplete = () => null,
}) => {
const [loading, setLoading] = useState(false)
const labels = useSelector(({ intl }) => intl.labels)
const dispatch = useDispatch()
const { register, handleSubmit, setValue, errors } = useForm()
const onSubmit = handleSubmit(({ description }) => {
setLoading(true)
const formData = new FormData()
formData.append('description', description)
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(data)
onClose()
})
.finally(() => setLoading(false))
})
useEffect(() => {
register('description', { required: true })
}, [])
useEffect(() => {
setValue('description', currentAnswer)
}, [currentAnswer])
return (
<Modal show={show}>
<Modal.Header className="pb-0">
<Modal.Title>
{currentAnswer
? labels.my_coach_answer_edit
: labels.my_coach_answer_add}
</Modal.Title>
</Modal.Header>
<Modal.Body>
{loading ? (
<Spinner />
) : (
<Form onSubmit={onSubmit}>
<CKEditor
onChange={(e) => setValue('description', e.editor.getData())}
onInstanceReady={(e) => e.editor.setData(currentAnswer)}
config={CKEDITOR_OPTIONS}
/>
{errors.description && (
<FormErrorFeedback>{labels.error_field_empty}</FormErrorFeedback>
)}
<Button className="mt-3 mr-2" variant="primary" type="submit">
{labels.accept}
</Button>
<Button className="btn-secondary mt-3" onClick={onClose}>
{labels.cancel}
</Button>
</Form>
)}
</Modal.Body>
</Modal>
)
}
export default AnswerModal