Proyectos de Subversion LeadersLinked - Antes de SPA

Rev

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

import React, { useEffect, useState } from 'react'
import { Button, Modal } from 'react-bootstrap'
import { useForm } from 'react-hook-form'
import { axios } from '../../utils'
import { addNotification } from '../../redux/notification/notification.actions'
import { useDispatch } from 'react-redux'

import Spinner from '../UI/Spinner'
import FormErrorFeedback from '../UI/FormErrorFeedback'
import DropzoneComponent from '../dropzone/DropzoneComponent'

const ImageModal = ({ show, onClose, sizes, id, onComplete }) => {
  const [loading, setLoading] = useState(false)
  const dispatch = useDispatch()

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

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

  const onSubmitHandler = ({ 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`,
    }

    setLoading(true)

    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).map(([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()
      })
      .finally(() => setLoading(false))
  }

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

  return (
    <Modal show={show} onHide={onClose}>
      <Modal.Header closeButton>
        <Modal.Title>Imagen</Modal.Title>
      </Modal.Header>
      <form
        encType="multipart/form-data"
        onSubmit={handleSubmit(onSubmitHandler)}
      >
        <Modal.Body>
          <DropzoneComponent
            modalType="IMAGE"
            onUploaded={onUploadedHandler}
            recomendationText={`Imágenes recomendadas de ${sizes}`}
          />
          {errors.image && (
            <FormErrorFeedback>{errors.image.message}</FormErrorFeedback>
          )}
        </Modal.Body>
        <Modal.Footer>
          <Button type="submit">Enviar</Button>
          <Button variant="danger" onClick={onClose}>
            Cancelar
          </Button>
        </Modal.Footer>
      </form>
      {loading && <Spinner />}
    </Modal>
  )
}

export default ImageModal