Proyectos de Subversion LeadersLinked - Antes de SPA

Rev

Rev 7190 | Ir a la última revisión | | Ultima modificación | Ver Log |

Rev Autor Línea Nro. Línea
7186 stevensc 1
import React, { useEffect, useState } from 'react'
2
import { Button, Form, Modal } from 'react-bootstrap'
3
import { useDispatch, useSelector } from 'react-redux'
4
import Spinner from '../UI/Spinner'
5
import { CKEditor } from 'ckeditor4-react'
6
import { CKEDITOR_OPTIONS, axios } from '../../utils'
7
import FormErrorFeedback from '../UI/FormErrorFeedback'
8
import { useForm } from 'react-hook-form'
9
import { addNotification } from '../../redux/notification/notification.actions'
10
 
11
const QuestionModal = ({ show, url, isEdit, onClose, onComplete }) => {
12
  const [loading, setLoading] = useState(false)
13
  const labels = useSelector(({ intl }) => intl.labels)
14
  const dispatch = useDispatch()
15
 
16
  const { register, handleSubmit, getValues, setValue, errors } = useForm()
17
 
18
  const onSubmit = handleSubmit((data) => {
19
    setLoading(true)
20
    const formData = new FormData()
21
    Object.entries(data).map(([key, value]) => {
22
      if (['attachment', 'image'].includes(key) && value) {
23
        formData.append(key, value[0])
24
        return
25
      }
26
      formData.append(key, value)
27
    })
28
 
29
    axios
30
      .post(url, formData)
31
      .then((response) => {
32
        const { data, success } = response.data
33
        if (!success) {
34
          if (typeof data === 'string') {
35
            dispatch(addNotification({ style: 'danger', msg: data }))
36
            return
37
          }
38
 
39
          Object.entries(data).map(([key, value]) => {
40
            key in getValues() &&
41
              dispatch(
42
                addNotification({
43
                  style: 'danger',
44
                  msg: `${key}: ${Array.isArray(value) ? value[0] : value}`,
45
                })
46
              )
47
          })
48
          return
49
        }
50
 
51
        onComplete()
52
        onClose()
53
      })
54
      .finally(() => setLoading(false))
55
  })
56
 
57
  useEffect(() => {
58
    register('description', { required: true })
59
  }, [])
60
 
61
  useEffect(() => {
62
    if (!url || !show || !isEdit) return
63
 
64
    axios.get(url).then((response) => {
65
      const { data, success } = response.data
66
 
67
      if (!success) {
68
        const errorMessage =
69
          typeof data === 'string' ? data : labels.error_there_was_an_error
70
 
71
        dispatch(
72
          addNotification({
73
            style: 'danger',
74
            msg: errorMessage,
75
          })
76
        )
77
        return
78
      }
79
 
80
      console.log(data)
81
 
82
      setValue('title', data.title)
83
      setValue('category_id', data.category_id)
84
      setValue('description', data.description)
85
    })
86
  }, [url, show, isEdit])
87
 
88
  useEffect(() => {
89
    if (!show) {
90
      setValue('category_id', '')
91
      setValue('description', '')
92
      setValue('title', '')
93
      setValue('image', '')
94
    }
95
  }, [show])
96
 
97
  return (
98
    <Modal show={show}>
99
      <Modal.Header className="pb-0">
100
        <Modal.Title>
101
          {isEdit ? labels.edit : labels.add} {labels.question}
102
        </Modal.Title>
103
      </Modal.Header>
104
      <Modal.Body>
105
        {loading ? (
106
          <Spinner />
107
        ) : (
108
          <Form onSubmit={onSubmit}>
109
            <Form.Group>
110
              <Form.Label>{labels.title}</Form.Label>
111
              <Form.Control
112
                type="text"
113
                name="title"
114
                ref={register({ required: true })}
115
              />
116
              {errors.title && (
117
                <FormErrorFeedback>
118
                  {labels.error_field_empty}
119
                </FormErrorFeedback>
120
              )}
121
            </Form.Group>
122
 
123
            <CKEditor
124
              onChange={(e) => setValue('description', e.editor.getData())}
125
              onInstanceReady={(e) =>
126
                e.editor.setData(getValues('description'))
127
              }
128
              config={CKEDITOR_OPTIONS}
129
            />
130
            {errors.description && (
131
              <FormErrorFeedback>{labels.error_field_empty}</FormErrorFeedback>
132
            )}
133
 
134
            <Button className="mt-3 mr-2" variant="primary" type="submit">
135
              {labels.accept}
136
            </Button>
137
            <Button className="btn-secondary mt-3" onClick={onClose}>
138
              {labels.cancel}
139
            </Button>
140
          </Form>
141
        )}
142
      </Modal.Body>
143
    </Modal>
144
  )
145
}
146
 
147
export default QuestionModal