Proyectos de Subversion LeadersLinked - SPA

Rev

Rev 2781 | Autoría | Ultima modificación | Ver Log |

import React, { useEffect } from 'react'
import { connect } from 'react-redux'
import { useForm } from 'react-hook-form'

import { useFetch } from '@hooks'
import { axios } from '@app/utils'
import { addNotification } from '@app/redux/notification/notification.actions'

import Widget from '@app/components/UI/Widget'
import Spinner from '@app/components/UI/Spinner'
import FormErrorFeedback from '@app/components/UI/form/FormErrorFeedback'
import SwitchInput from '@app/components/UI/SwitchInput'

const BasicSettings = ({
  addNotification = function () {} // Redux action
}) => {
  const { data: timezones } = useFetch('/helpers/timezones')
  const { data, isLoading } = useFetch('/account-settings/basic')

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

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

    axios
      .post('/account-settings/basic', formData)
      .then(({ data: responseData }) => {
        const { data, success } = responseData

        if (!success) {
          const errorMessage =
            typeof data === 'string'
              ? data
              : Object.entries(data)
                  .map(([key, value]) => `${key}: ${value}`)
                  .join(', ')

          throw new Error(errorMessage)
        }

        addNotification({ style: 'success', msg: data })
      })
      .catch((err) => {
        addNotification({ style: 'danger', msg: err.message })
      })
  }

  useEffect(() => {
    register('timezone', { required: 'Por favor ingrese su zona horaria' })
  }, [])

  useEffect(() => {
    Object.entries(data).forEach(([key, value]) => {
      const currentValue = getValues(key)

      if (!currentValue) register(key, { required: true })
      setValue(key, key === 'is_adult' ? value === 'y' : value)
    })
  }, [data])

  if (isLoading) {
    return <Spinner />
  }

  return (
    <Widget>
      <Widget.Header title='Información básica' />

      <Widget.Body>
        <form onSubmit={handleSubmit(onSubmit)}>
          <div className='inputs__container'>
            <div className='cp-field'>
              <label htmlFor='first_name'>Nombre</label>
              <input
                type='text'
                name='first_name'
                ref={register}
                defaultValue={watch('first_name')}
              />
              {errors.first_name && (
                <FormErrorFeedback>
                  Por favor ingrese su nombre
                </FormErrorFeedback>
              )}
            </div>
            <div className='cp-field'>
              <label htmlFor='last_name'>Apellido</label>
              <input
                type='text'
                name='last_name'
                ref={register}
                defaultValue={watch('last_name')}
              />
              {errors.last_name && (
                <FormErrorFeedback>
                  Por favor ingrese su apellido
                </FormErrorFeedback>
              )}
            </div>
          </div>

          <div className='inputs__container'>
            <div className='cp-field'>
              <label htmlFor='email'>Email</label>
              <input
                type='text'
                name='email'
                ref={register}
                defaultValue={watch('email')}
              />
              {errors.email && (
                <FormErrorFeedback>
                  Por favor ingrese un correo electrónico valido
                </FormErrorFeedback>
              )}
            </div>
            <div className='cp-field'>
              <label htmlFor='phone'>Teléfono</label>
              <input
                name='phone'
                ref={register({
                  required: 'Por favor ingrese su número de teléfono',
                  pattern: {
                    message: 'Por favor ingrese un número de teléfono válido',
                    value:
                      /^\+[1-9]{1}[0-9]{0,2}[2-9]{1}[0-9]{2}[2-9]{1}[0-9]{2}[0-9]{4}$/
                  }
                })}
                defaultValue={watch('phone')}
              />
              {errors.phone && (
                <FormErrorFeedback>{errors.phone.message}</FormErrorFeedback>
              )}
            </div>
          </div>

          <div className='inputs__container'>
            <div className='cp-field'>
              <label htmlFor='gender'>Género</label>
              <select
                defaultValue={watch('gender')}
                name='gender'
                ref={register}
              >
                <option value='' hidden>
                  Seleccione un género
                </option>
                <option value='m'>Masculino</option>
                <option value='f'>Femenino</option>
              </select>
              {errors.gender && (
                <FormErrorFeedback>
                  Por favor selecciona un genero
                </FormErrorFeedback>
              )}
            </div>

            <div className='cp-field'>
              <label htmlFor='timezone'>Zona horaria</label>
              <select
                name='timezone'
                ref={register}
                defaultValue={watch('timezone')}
              >
                <option value='' hidden>
                  Zona horaria
                </option>
                {Object.entries(timezones).map(([key, value]) => (
                  <option value={key} key={key}>
                    {value}
                  </option>
                ))}
              </select>
              {errors.timezone && (
                <FormErrorFeedback>
                  Por favor selecciona una zona horaria
                </FormErrorFeedback>
              )}
            </div>
          </div>

          <div className='cp-field'>
            <label htmlFor='timezone'>Eres mayor de 18</label>
            <SwitchInput
              isChecked={watch('is_adult')}
              setValue={(value) => setValue('is_adult', value)}
            />
          </div>

          <button type='submit' className='btn btn-primary mt-3'>
            Guardar
          </button>
        </form>
      </Widget.Body>
    </Widget>
  )
}

const mapDispatchToProps = {
  addNotification: (notification) => addNotification(notification)
}

export default connect(null, mapDispatchToProps)(BasicSettings)