Rev 3432 | Autoría | Comparar con el anterior | Ultima modificación | Ver Log |
import React, { useEffect, useState } from 'react';
import { connect } from 'react-redux';
import { Avatar } from '@mui/material';
import { axios } from '@app/utils';
import { addNotification } from '@app/redux/notification/notification.actions';
import Button from '@app/components/UI/buttons/Buttons';
import Widget from '@app/components/UI/Widget';
import Spinner from '@app/components/UI/Spinner';
import DropzoneComponent from '@app/components/dropzone/DropzoneComponent';
import FormErrorFeedback from '@app/components/UI/form/FormErrorFeedback';
const ChangeImage = ({ addNotification }) => {
const [imageUrl, setImageUrl] = useState('');
const [imageFile, setImageFile] = useState(null);
const [loading, setLoading] = useState(false);
const [error, setError] = useState('');
const handleOnDropImage = (acceptedFile) => {
if (!acceptedFile) {
setImageUrl('');
setImageFile(null);
setError('');
return;
}
setError('');
const newImgUrl = URL.createObjectURL(acceptedFile);
setImageUrl(newImgUrl);
setImageFile(acceptedFile);
};
const handleSubmit = async () => {
if (!validate()) return;
setLoading(true);
const formData = new FormData();
formData.append('image', imageFile);
axios
.post('/account-settings/image/upload', formData)
.then((response) => {
const { data, success } = response.data;
if (!success) {
const errorMessage =
typeof data === 'string' ? data : 'Ha ocurrido un error, Por favor intente más tarde';
throw new Error(errorMessage);
}
sessionStorage.setItem('user_session_image', data);
addNotification({
style: 'success',
msg: 'Imagen cambiada exitosamente'
});
})
.catch((err) => addNotification({ style: 'danger', msg: err.message }))
.finally(() => setLoading(false));
};
const validate = () => {
let errorMsg = '';
if (!imageFile) {
errorMsg = 'Por favor ingrese una imagen';
setError(errorMsg);
return false;
}
return true;
};
const getUserImage = () => {
setLoading(true);
axios
.get('/account-settings/image/upload')
.then((response) => {
const { data, success } = response.data;
if (!success) {
throw new Error(data);
}
setImageUrl(data);
})
.catch((err) => {
addNotification({ style: 'danger', msg: err.message });
})
.finally(() => setLoading(false));
};
useEffect(() => {
getUserImage();
}, []);
return (
<Widget>
<Widget.Header title='Cambiar Imagen' />
<Widget.Body>
{imageUrl && <Avatar src={imageUrl} sx={{ width: 100, height: 100, margin: 'auto' }} />}
<DropzoneComponent onUploaded={handleOnDropImage} modalType='IMAGE' />
{error ? <FormErrorFeedback>{error}</FormErrorFeedback> : null}
{loading && <Spinner />}
<Button color='primary' onClick={handleSubmit} styles={{ marginTop: '1rem' }} fullWidth>
Guardar
</Button>
</Widget.Body>
</Widget>
);
};
const mapDispatchToProps = {
addNotification: (notification) => addNotification(notification)
};
export default connect(null, mapDispatchToProps)(ChangeImage);