Proyectos de Subversion LeadersLinked - Antes de SPA

Rev

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

Rev Autor Línea Nro. Línea
5489 stevensc 1
import React, { useEffect, useState } from 'react'
2
import { Button, Modal } from 'react-bootstrap'
3
import { axios } from '../../../utils'
4
import { useForm } from 'react-hook-form'
5
import { useDispatch } from 'react-redux'
6
import { addNotification } from '../../../redux/notification/notification.actions'
7
 
8
import Spinner from '../../../shared/loading-spinner/Spinner'
9
import TagsInput from '../../../shared/tags-input/TagsInput'
10
import FormErrorFeedback from '../../../shared/form-error-feedback/FormErrorFeedback'
11
 
12
const HobbiesModal = ({
13
  show = false,
14
  userIdEncrypted = '',
15
  userHobbiesAndInterests = [],
16
  hobbiesAndInterestsOptions = [],
17
  closeModal = () => {},
18
  setUserHobbiesAndInterests = () => {},
19
}) => {
20
  const { register, errors, handleSubmit, setValue, getValues, setError } =
21
    useForm()
22
  const [modalLoading, setModalLoading] = useState(false)
23
  const [settedHobbyAndInterestTags, setSettedHobbyAndInterestTags] = useState(
24
    []
25
  )
26
  const dispatch = useDispatch()
27
 
28
  const handleModalOpen = (event) => {
29
    event && event.preventDefault()
30
    Object.keys(getValues()).map(([key]) => setValue(key, ''))
31
    closeModal()
32
  }
33
 
34
  const handleTagsChange = (tags) => {
35
    if (tags.length) {
36
      let newTags = []
37
      tags.map((tag) => {
38
        newTags = [...newTags, tag.value]
39
      })
40
      setValue('hobbiesAndInterests', newTags)
41
      setSettedHobbyAndInterestTags(tags)
42
    } else {
43
      setValue('hobbiesAndInterests', '')
44
      setSettedHobbyAndInterestTags('')
45
    }
46
  }
47
 
48
  const onSubmitHandler = async () => {
49
    setModalLoading(true)
50
    const formData = new FormData()
51
    getValues('hobbiesAndInterests').map((language) => {
52
      formData.append('hobbies_and_interests[]', language)
53
    })
54
    await axios
55
      .post(
56
        `/profile/my-profiles/hobby-and-interest/${userIdEncrypted}`,
57
        formData
58
      )
59
      .then((response) => {
60
        const resData = response.data
61
        if (resData.success) {
62
          setUserHobbiesAndInterests(settedHobbyAndInterestTags)
63
          dispatch(
64
            addNotification({ style: 'success', msg: 'Registro actualizado' })
65
          )
66
          handleModalOpen()
67
        } else {
68
          const resError = resData.data
69
          if (resError.constructor.name === 'Object') {
70
            Object.entries(resError).map(([key, value]) => {
71
              if (key in getValues()) {
72
                setError(key, {
73
                  type: 'manual',
74
                  message: Array.isArray(value) ? value[0] : value,
75
                })
76
              }
77
            })
78
          } else {
79
            dispatch(addNotification({ style: 'danger', msg: resError }))
80
          }
81
        }
82
      })
83
    setModalLoading(false)
84
  }
85
 
86
  useEffect(() => {
87
    register('hobbiesAndInterests', {
88
      required: 'Por favor seleccione al menos un pasatiempo o interés',
89
    })
90
  }, [])
91
 
92
  return (
93
    <Modal show={show} onHide={handleModalOpen}>
94
      <Modal.Header closeButton>
95
        <Modal.Title>Pasatiempos e intereses</Modal.Title>
96
      </Modal.Header>
97
      <form onSubmit={handleSubmit(onSubmitHandler)}>
98
        <Modal.Body>
99
          <div className="form-group">
100
            <TagsInput
101
              suggestions={hobbiesAndInterestsOptions}
102
              settedTags={userHobbiesAndInterests}
103
              onChange={handleTagsChange}
104
            />
105
            {errors.hobbiesAndInterests && (
106
              <FormErrorFeedback>
107
                {errors.hobbiesAndInterests.message}
108
              </FormErrorFeedback>
109
            )}
110
          </div>
111
        </Modal.Body>
112
        <Modal.Footer>
113
          <Button size="sm" type="submit">
114
            Enviar
115
          </Button>
116
          <Button size="sm" variant="danger" onClick={handleModalOpen}>
117
            Cancelar
118
          </Button>
119
        </Modal.Footer>
120
      </form>
121
      {modalLoading && <Spinner />}
122
    </Modal>
123
  )
124
}
125
 
126
export default HobbiesModal