Proyectos de Subversion LeadersLinked - SPA

Rev

Rev 3434 | | Comparar con el anterior | Ultima modificación | Ver Log |

Rev Autor Línea Nro. Línea
3719 stevensc 1
import React from 'react';
2
import { useDispatch } from 'react-redux';
3
import { Controller, useForm } from 'react-hook-form';
4
 
5
import { axios } from '@utils';
6
import { addNotification } from '@store/notification/notification.actions';
7
 
8
import Modal from '@components/UI/modal/Modal';
9
import DropzoneComponent from '@components/dropzone/DropzoneComponent';
10
import FormErrorFeedback from '@components/UI/form/FormErrorFeedback';
11
 
12
const ImageModal = ({
13
  show = false,
14
  url = '',
15
  message = 'Imágenes recomendadas de 250x250',
16
  onComplete = () => {},
17
  onClose = () => {}
18
}) => {
19
  const dispatch = useDispatch();
20
 
21
  const {
22
    control,
23
    formState: { isSubmitting },
24
    handleSubmit,
25
    reset
26
  } = useForm({
27
    defaultValues: { image: '' }
28
  });
29
 
30
  const onSubmit = handleSubmit(async (image) => {
31
    try {
32
      const response = await axios.post(url, image);
33
      const { data, success } = response.data;
34
      if (!success) throw new Error('Error al actualizar la imagen');
35
 
36
      const newImage = data.profile ?? data;
37
 
38
      if (data.update_navbar) sessionStorage.setItem('user_session_image', data.user);
39
 
40
      dispatch(addNotification({ style: 'success', msg: 'Imagen actualizada' }));
41
      onComplete(newImage);
42
      reset();
43
      onClose();
44
    } catch (error) {
45
      dispatch(addNotification({ style: 'danger', msg: error.message }));
46
    }
47
  });
48
 
49
  return (
50
    <Modal
51
      show={show}
52
      title='Imagen'
53
      onClose={onClose}
54
      onReject={onClose}
55
      onAccept={onSubmit}
56
      loading={isSubmitting}
57
    >
58
      <Controller
59
        name='image'
60
        control={control}
61
        rules={{ required: 'Imagen requerida' }}
62
        render={({ field: { onChange, value }, fieldState: { error } }) => (
63
          <>
64
            <DropzoneComponent
65
              type='IMAGE'
66
              onUploaded={(file) => onChange(file)}
67
              settedFile={value}
68
              recomendationText={message}
69
            />
70
            {error && <FormErrorFeedback>{error.message}</FormErrorFeedback>}
71
          </>
72
        )}
73
      />
74
    </Modal>
75
  );
76
};
77
 
78
export default ImageModal;