Proyectos de Subversion LeadersLinked - Antes de SPA

Rev

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

import { CKEditor } from 'ckeditor4-react'
import React, { useEffect, useState } from 'react'
import { Button, Form, Modal } from 'react-bootstrap'
import { useDispatch, useSelector } from 'react-redux'
import { CKEDITOR_OPTIONS, axios } from '../../utils'
import { useForm } from 'react-hook-form'
import FormErrorFeedback from '../UI/FormErrorFeedback'
import { addNotification } from '../../redux/notification/notification.actions'

const KnowledgeEditModal = ({
  show,
  categories = [],
  url,
  onComplete,
  onClose,
}) => {
  const [loading, setLoading] = useState(false)
  const labels = useSelector(({ intl }) => intl.labels)
  const dispatch = useDispatch()

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

  const onSubmit = handleSubmit((data) => {
    setLoading(true)
    const formData = new FormData()
    Object.entries(data).map(([key, value]) => formData.append(key, value))

    axios
      .post(url, formData)
      .then((response) => {
        const { data, success } = response.data
        if (!success) {
          if (typeof data === 'string') {
            dispatch(addNotification({ style: 'danger', msg: data }))
            return
          }

          Object.entries(data).map(([key, value]) => {
            key in getValues() &&
              dispatch(
                addNotification({
                  style: 'danger',
                  msg: `${key}: ${Array.isArray(value) ? value[0] : value}`,
                })
              )
          })
          return
        }

        onComplete()
        onClose()
      })
      .finally(() => setLoading(false))
  })

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

  useEffect(() => {
    if (!url) return

    axios.get(url).then((response) => {
      const { data, success } = response.data

      if (!success) {
        const errorMessage =
          typeof data === 'string' ? data : 'Ha ocurrido un error'

        dispatch(
          addNotification({
            style: 'danger',
            msg: errorMessage,
          })
        )
        return
      }

      setValue('category_id', data.category_id)
      setValue('description', data.description)
      setValue('title', data.title)
    })
  }, [show])

  return (
    <Modal show={show}>
      <Modal.Header className="pb-0">
        <Modal.Title>Editar conocimiento</Modal.Title>
      </Modal.Header>
      <Modal.Body>
        <Form onSubmit={onSubmit}>
          <Form.Group>
            <Form.Label>{labels.category}</Form.Label>
            <Form.Control
              as="select"
              ref={register({ required: true })}
              name="category_id"
            >
              {categories.map(({ name, uuid }) => (
                <option value={uuid} key={uuid}>
                  {name}
                </option>
              ))}
            </Form.Control>
            {errors.category_id && (
              <FormErrorFeedback>{labels.error_field_empty}</FormErrorFeedback>
            )}
          </Form.Group>

          <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>

          <CKEditor
            onChange={(e) => setValue('description', e.editor.getData())}
            onInstanceReady={(e) => e.editor.setData(getValues('description'))}
            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 KnowledgeEditModal