Proyectos de Subversion LeadersLinked - Antes de SPA

Rev

| Ultima modificación | Ver Log |

Rev Autor Línea Nro. Línea
6794 stevensc 1
import React, { useEffect, useState } from 'react'
2
import { Button, Modal } from 'react-bootstrap'
3
import { useForm } from 'react-hook-form'
4
import { axios } from '../../utils'
5
import { addNotification } from '../../redux/notification/notification.actions'
6
import { useDispatch } from 'react-redux'
7
 
8
import Spinner from '../UI/Spinner'
9
import FormErrorFeedback from '../UI/FormErrorFeedback'
10
import DropzoneComponent from '../dropzone/DropzoneComponent'
11
 
12
const ImageModal = ({ show, onClose, sizes, id, onComplete }) => {
13
  const [loading, setLoading] = useState(false)
14
  const dispatch = useDispatch()
15
 
16
  const {
17
    register,
18
    errors,
19
    handleSubmit,
20
    setValue,
21
    clearErrors,
22
    setError,
23
    getValues,
24
  } = useForm()
25
 
26
  const onUploadedHandler = (files) => {
27
    setValue('image', files)
28
    clearErrors('image')
29
  }
30
 
31
  const onSubmitHandler = ({ image }) => {
32
    const type = window.location.pathname.split('/')[1]
33
    const typesUrl = {
34
      profile: `/profile/my-profiles/image/${id}/operation/upload`,
35
      company: `/my-company/${id}/profile/image/upload`,
36
      group: `/group/my-groups/image/${id}/operation/upload`,
37
    }
38
 
39
    setLoading(true)
40
 
41
    const formData = new FormData()
42
    formData.append('image', image)
43
 
44
    axios
45
      .post(typesUrl[type], formData)
46
      .then(({ data: response }) => {
47
        const { data, success } = response
48
 
49
        if (!success) {
50
          const resError = data
51
          if (resError.constructor.name === 'Object') {
52
            Object.entries(resError).map(([key, value]) => {
53
              if (key in getValues()) {
54
                setError(key, {
55
                  type: 'manual',
56
                  message: Array.isArray(value) ? value[0] : value,
57
                })
58
              }
59
            })
60
          } else {
61
            dispatch(addNotification({ style: 'danger', msg: resError }))
62
          }
63
        }
64
 
65
        const newImage = data.profile ?? data
66
 
67
        if (data.update_navbar) {
68
          sessionStorage.setItem('user_session_image', data.user)
69
        }
70
 
71
        onComplete(newImage)
72
 
73
        setValue('image', '')
74
        dispatch(
75
          addNotification({ style: 'success', msg: 'Registro actualizado' })
76
        )
77
        onClose()
78
      })
79
      .finally(() => setLoading(false))
80
  }
81
 
82
  useEffect(() => {
83
    register('image', {
84
      required: { value: 'true', message: 'El campo es requerido' },
85
    })
86
  }, [])
87
 
88
  return (
89
    <Modal show={show} onHide={onClose}>
90
      <Modal.Header closeButton>
91
        <Modal.Title>Imagen</Modal.Title>
92
      </Modal.Header>
93
      <form
94
        encType="multipart/form-data"
95
        onSubmit={handleSubmit(onSubmitHandler)}
96
      >
97
        <Modal.Body>
98
          <DropzoneComponent
99
            modalType="IMAGE"
100
            onUploaded={onUploadedHandler}
101
            recomendationText={`Imágenes recomendadas de ${sizes}`}
102
          />
103
          {errors.image && (
104
            <FormErrorFeedback>{errors.image.message}</FormErrorFeedback>
105
          )}
106
        </Modal.Body>
107
        <Modal.Footer>
108
          <Button type="submit">Enviar</Button>
109
          <Button variant="danger" onClick={onClose}>
110
            Cancelar
111
          </Button>
112
        </Modal.Footer>
113
      </form>
114
      {loading && <Spinner />}
115
    </Modal>
116
  )
117
}
118
 
119
export default ImageModal