Proyectos de Subversion LeadersLinked - SPA

Rev

| Ultima modificación | Ver Log |

Rev Autor Línea Nro. Línea
2781 stevensc 1
import React, { useEffect, useState } from 'react'
2
import { connect } from 'react-redux'
3
import { useForm } from 'react-hook-form'
4
 
5
import { useFetch } from '@hooks'
6
import { axios } from '@app/utils'
7
import { addNotification } from '@app/redux/notification/notification.actions'
8
 
9
import Widget from '@app/components/UI/Widget'
10
import Spinner from '@app/components/UI/Spinner'
11
import FormErrorFeedback from '@app/components/UI/form/FormErrorFeedback'
12
import SwitchInput from '@app/components/UI/SwitchInput'
13
 
14
const BasicSettings = ({
15
  addNotification = function () {} // Redux action
16
}) => {
17
  const { data: timezones } = useFetch('/helpers/timezones', {})
18
  const [loading, setLoading] = useState(false)
19
  const [isAdult, setIsAdult] = useState(false)
20
 
21
  const { register, handleSubmit, setValue, watch, errors, getValues } =
22
    useForm()
23
 
24
  const onSubmit = async (data) => {
25
    setLoading(true)
26
    const formData = new FormData()
27
 
28
    formData.append('is_adult', isAdult ? 'y' : 'n')
29
    Object.entries(data).map(([key, value]) => formData.append(key, value))
30
 
31
    axios
32
      .post('/account-settings/basic', formData)
33
      .then(({ data: responseData }) => {
34
        const { data, success } = responseData
35
 
36
        if (!success) {
37
          const errorMessage =
38
            typeof data === 'string'
39
              ? data
40
              : Object.entries(data)
41
                  .map(([key, value]) => `${key}: ${value}`)
42
                  .join(', ')
43
 
44
          throw new Error(errorMessage)
45
        }
46
 
47
        addNotification({ style: 'success', msg: data })
48
      })
49
      .catch((err) => {
50
        addNotification({ style: 'danger', msg: err.message })
51
      })
52
      .finally(() => setLoading(false))
53
  }
54
 
55
  const getBasicSettings = () => {
56
    setLoading(true)
57
 
58
    axios
59
      .get('/account-settings/basic')
60
      .then(({ data: responseData }) => {
61
        const { data, success } = responseData
62
 
63
        if (success) {
64
          Object.entries(data).forEach(([key, value]) => {
65
            const currentValue = getValues(key)
66
 
67
            if (key === 'is_adult') {
68
              return setIsAdult(value === 'y')
69
            }
70
 
71
            if (!currentValue) {
72
              register(key, { required: true })
73
            }
74
 
75
            setValue(key, value)
76
          })
77
        }
78
      })
79
      .catch((err) => {
80
        addNotification({ style: 'danger', msg: err.message })
81
      })
82
      .finally(() => setLoading(false))
83
  }
84
 
85
  useEffect(() => {
86
    register('timezone', {
87
      required: 'Por favor ingrese su zona horaria'
88
    })
89
 
90
    getBasicSettings()
91
  }, [])
92
 
93
  return (
94
    <Widget>
95
      <Widget.Header title='Información básica' />
96
 
97
      <Widget.Body>
98
        {loading ? (
99
          <Spinner />
100
        ) : (
101
          <form onSubmit={handleSubmit(onSubmit)}>
102
            <div className='inputs__container'>
103
              <div className='cp-field'>
104
                <label htmlFor='first_name'>Nombre</label>
105
                <input
106
                  type='text'
107
                  name='first_name'
108
                  ref={register}
109
                  defaultValue={watch('first_name')}
110
                />
111
                {errors.first_name && (
112
                  <FormErrorFeedback>
113
                    Por favor ingrese su nombre
114
                  </FormErrorFeedback>
115
                )}
116
              </div>
117
              <div className='cp-field'>
118
                <label htmlFor='last_name'>Apellido</label>
119
                <input
120
                  type='text'
121
                  name='last_name'
122
                  ref={register}
123
                  defaultValue={watch('last_name')}
124
                />
125
                {errors.last_name && (
126
                  <FormErrorFeedback>
127
                    Por favor ingrese su apellido
128
                  </FormErrorFeedback>
129
                )}
130
              </div>
131
            </div>
132
 
133
            <div className='inputs__container'>
134
              <div className='cp-field'>
135
                <label htmlFor='email'>Email</label>
136
                <input
137
                  type='text'
138
                  name='email'
139
                  ref={register}
140
                  defaultValue={watch('email')}
141
                />
142
                {errors.email && (
143
                  <FormErrorFeedback>
144
                    Por favor ingrese un correo electrónico valido
145
                  </FormErrorFeedback>
146
                )}
147
              </div>
148
              <div className='cp-field'>
149
                <label htmlFor='phone'>Teléfono</label>
150
                <input
151
                  name='phone'
152
                  ref={register({
153
                    required: 'Por favor ingrese su número de teléfono',
154
                    pattern: {
155
                      message: 'Por favor ingrese un número de teléfono válido',
156
                      value:
157
                        /^\+[1-9]{1}[0-9]{0,2}[2-9]{1}[0-9]{2}[2-9]{1}[0-9]{2}[0-9]{4}$/
158
                    }
159
                  })}
160
                  defaultValue={watch('phone')}
161
                />
162
                {errors.phone && (
163
                  <FormErrorFeedback>{errors.phone.message}</FormErrorFeedback>
164
                )}
165
              </div>
166
            </div>
167
 
168
            <div className='inputs__container'>
169
              <div className='cp-field'>
170
                <label htmlFor='gender'>Género</label>
171
                <select
172
                  defaultValue={watch('gender')}
173
                  name='gender'
174
                  ref={register}
175
                >
176
                  <option value='' hidden>
177
                    Seleccione un género
178
                  </option>
179
                  <option value='m'>Masculino</option>
180
                  <option value='f'>Femenino</option>
181
                </select>
182
                {errors.gender && (
183
                  <FormErrorFeedback>
184
                    Por favor selecciona un genero
185
                  </FormErrorFeedback>
186
                )}
187
              </div>
188
 
189
              <div className='cp-field'>
190
                <label htmlFor='timezone'>Zona horaria</label>
191
                <select
192
                  name='timezone'
193
                  ref={register}
194
                  defaultValue={watch('timezone')}
195
                >
196
                  <option value='' hidden>
197
                    Zona horaria
198
                  </option>
199
                  {Object.entries(timezones).map(([key, value]) => (
200
                    <option value={key} key={key}>
201
                      {value}
202
                    </option>
203
                  ))}
204
                </select>
205
                {errors.timezone && (
206
                  <FormErrorFeedback>
207
                    Por favor selecciona una zona horaria
208
                  </FormErrorFeedback>
209
                )}
210
              </div>
211
            </div>
212
 
213
            <div className='cp-field'>
214
              <label htmlFor='timezone'>Eres mayor de 18</label>
215
              <SwitchInput
216
                isChecked={isAdult}
217
                setValue={(value) => setIsAdult(value)}
218
              />
219
            </div>
220
 
221
            <button type='submit' className='btn btn-primary mt-3'>
222
              Guardar
223
            </button>
224
          </form>
225
        )}
226
      </Widget.Body>
227
    </Widget>
228
  )
229
}
230
 
231
const mapDispatchToProps = {
232
  addNotification: (notification) => addNotification(notification)
233
}
234
 
235
export default connect(null, mapDispatchToProps)(BasicSettings)