Proyectos de Subversion LeadersLinked - SPA

Rev

Rev 2781 | Rev 3432 | Ir a la última revisión | Autoría | Comparar con el anterior | Ultima modificación | Ver Log |

import React, { useEffect, useState } from 'react'
import { connect } from 'react-redux'
import { useForm } from 'react-hook-form'
import { styled } from '@mui/material'

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

import Spinner from '@components/UI/Spinner'
import UbicationInput from '@components/UI/inputs/UbicationInput'
import FormErrorFeedback from '@components/UI/form/FormErrorFeedback'

const StyledSpinnerContainer = styled('div')`
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  background: rgba(255, 255, 255, 0.4);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 300;
`

const Location = ({ addNotification }) => {
  const [loading, setLoading] = useState(false)

  const {
    register,
    handleSubmit,
    setValue,
    clearErrors,
    watch,
    setError,
    formState: { errors }
  } = useForm()

  const getLocations = () => {
    axios
      .get('account-settings/location')
      .then(({ data: responseData }) => {
        const { data, success } = responseData

        if (!success) {
          throw new Error('Error interno. Por favor, intente mas tarde')
        }

        Object.entries(data).forEach(([key, value]) => {
          setValue(key, value)
        })
      })
      .catch((err) => {
        addNotification({ style: 'danger', msg: err.message })
      })
  }

  const getAddress = (address) => {
    Object.entries(address).forEach(([key, value]) => {
      if (value) {
        register(key)
        clearErrors(key)
        setValue(key, value)
      }
    })
  }

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

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

        if (success) {
          addNotification({
            style: 'success',
            msg: data.message
          })
        } else {
          if (typeof data === 'object') {
            Object.entries(data).forEach(([key, value]) => {
              setError(key, { type: 'manual', message: value[0] })
            })
          } else {
            const errorMessage =
              typeof data === 'string'
                ? data
                : 'Ha ocurrido un error, Por favor intente mas tarde'
            addNotification({
              style: 'danger',
              msg: errorMessage
            })
          }
        }
      })
    setLoading(false)
  }

  useEffect(() => {
    getLocations()

    register('formatted_address', {
      required: 'por favor seleccione una ubicación correcta'
    })
  }, [])

  return (
    <div className='settings-container'>
      <h2>Cambiar Ubicación</h2>
      <div className='acc-setting_content'>
        <form onSubmit={handleSubmit(onSubmit)}>
          <div className='d-flex flex-wrap' style={{ gap: '1rem' }}>
            <div className='cp-field cp-field2'>
              <label htmlFor='first_name'>Ubicación</label>
              <div className='cpp-fiel'>
                <UbicationInput
                  onGetAddress={getAddress}
                  settedQuery={watch('formatted_address')}
                />
                <i className='fa fa-map-marker'></i>
              </div>
              {
                <FormErrorFeedback>
                  {errors?.formatted_address?.message}
                </FormErrorFeedback>
              }
            </div>
            <div className='col-2 mx-auto d-flex align-items-center justify-content-center'>
              <button type='submit' className='btn btn-secondary mt-3'>
                Guardar
              </button>
            </div>
          </div>
        </form>
      </div>
      {loading && (
        <StyledSpinnerContainer>
          <Spinner />
        </StyledSpinnerContainer>
      )}
    </div>
  )
}

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

export default connect(null, mapDispatchToProps)(Location)