Proyectos de Subversion LeadersLinked - SPA

Rev

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

import React, { useEffect } from 'react'
import { useDispatch, useSelector } from 'react-redux'
import { useForm } from 'react-hook-form'
import { CKEditor } from 'ckeditor4-react'

import { CKEDITOR_OPTIONS, axios } from 'utils/index'
import { addNotification } from '../../redux/notification/notification.actions'

import Modal from 'components/UI/modal/Modal'
import FormErrorFeedback from 'components/UI/form/FormErrorFeedback'

const AnswerModal = ({
  show = false,
  currentAnswer = '',
  url = '',
  onClose = () => null,
  onComplete = () => null
}) => {
  const labels = useSelector(({ intl }) => intl.labels)
  const dispatch = useDispatch()

  const { register, handleSubmit, setValue, errors } = useForm()

  const onSubmit = handleSubmit(({ description }) => {
    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()
      })
  })

  useEffect(() => {
    register('description', { required: true })
  }, [])

  useEffect(() => {
    setValue('description', currentAnswer)
  }, [currentAnswer])

  return (
    <Modal
      title={
        currentAnswer ? labels.my_coach_answer_edit : labels.my_coach_answer_add
      }
      show={show}
      onClose={onClose}
      onAccept={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>
      )}

    </Modal>
  )
}

export default AnswerModal