Proyectos de Subversion LeadersLinked - SPA

Rev

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

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

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

import Modal from 'components/UI/Modal'
import DropzoneComponent from '../dropzone/DropzoneComponent'
import FormErrorFeedback from '../UI/FormErrorFeedback'

const ImageModal = ({ show, onClose, sizes, id, onComplete }) => {
  const dispatch = useDispatch()

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

  const onUploadedHandler = (files) => {
    setValue('image', files)
    clearErrors('image')
  }

  const onSubmitHandler = handleSubmit(({ image }) => {
    const type = window.location.pathname.split('/')[1]
    const typesUrl = {
      profile: `/profile/my-profiles/image/${id}/operation/upload`,
      company: `/my-company/${id}/profile/image/upload`,
      group: `/group/my-groups/image/${id}/operation/upload`
    }

    const formData = new FormData()
    formData.append('image', image)

    axios.post(typesUrl[type], formData).then(({ data: response }) => {
      const { data, success } = response

      if (!success) {
        const resError = data
        if (resError.constructor.name === 'Object') {
          Object.entries(resError).forEach(([key, value]) => {
            if (key in getValues()) {
              setError(key, {
                type: 'manual',
                message: Array.isArray(value) ? value[0] : value
              })
            }
          })
        } else {
          dispatch(addNotification({ style: 'danger', msg: resError }))
        }
      }

      const newImage = data.profile ?? data

      if (data.update_navbar) {
        sessionStorage.setItem('user_session_image', data.user)
      }

      onComplete(newImage)

      setValue('image', '')
      dispatch(
        addNotification({ style: 'success', msg: 'Registro actualizado' })
      )
      onClose()
    })
  })

  useEffect(() => {
    register('image', {
      required: { value: 'true', message: 'El campo es requerido' }
    })
  }, [])

  return (
    <Modal
      show={show}
      title='Imagen'
      onClose={onClose}
      onReject={onClose}
      onAccept={onSubmitHandler}
    >
      <DropzoneComponent
        modalType='IMAGE'
        onUploaded={onUploadedHandler}
        recomendationText={`Imágenes recomendadas de ${sizes}`}
      />

      {errors.image && (
        <FormErrorFeedback>{errors.image.message}</FormErrorFeedback>
      )}
    </Modal>
  )
}

export default ImageModal