Proyectos de Subversion LeadersLinked - Antes de SPA

Rev

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

import {axios} from "../../../utils";
import React, { useEffect, useState } from "react";
import { connect } from "react-redux";
import styled from "styled-components";
import { addNotification } from "../../../redux/notification/notification.actions";
import FormErrorFeedback from "../../../shared/form-error-feedback/FormErrorFeedback";
import Spinner from "../../../shared/loading-spinner/Spinner";
import MyDropzone from "./dropzone/Dropzone";

const StyledSetting = styled.div`
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
  margin: 2rem;
  .dropzoneContainer {
    width: 90%;
    height: 100px;
    margin-top: 1.5rem;
  }
`;

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 ChangeImage = (props) => {
  // redux destructuring
  const { addNotification } = props;

  // states
  const [imageUrl, setImageUrl] = useState("");
  const [imageFile, setImageFile] = useState(null);
  const [error, setError] = useState("");
  const [loading, setLoading] = useState(false);

  const handleOnDropImage = (acceptedFile) => {
    setError("");
    const newImgUrl = URL.createObjectURL(acceptedFile);
    setImageUrl(newImgUrl);
    setImageFile(acceptedFile);
  };

  const handleDropReject = () => {
    setError("Por favor solo introducir imagenes jpeg, jpeg y png");
  };

  const handleSubmit = async () => {
    setLoading(true);
    if (validate()) {
      const formData = new FormData();
      formData.append("image", imageFile);
      await axios
        .post("/account-settings/image/upload", formData)
        .then((response) => {
          const resData = response.data;
          if (resData.success) {
            addNotification({
              style: "success",
              msg: 'Imagen cambiada exitosamente',
            });
          } else {
            const errorMsg =
              typeof resData.data === "string"
                ? resData.data
                : "Ha ocurrido un error, Por favor intente más tarde";
            addNotification({
              style: "danger",
              msg: errorMsg,
            });
          }
        });
    }
    setLoading(false);
  };

  const validate = () => {
    let errorMsg = "";
    if (!imageFile) {
      errorMsg = "Por favor ingrese una imagen";
      setError(errorMsg);
      return false;
    }
    return true;
  };

  useEffect(async () => {
    setLoading(true);
    await axios.get("/account-settings/image/upload").then((response) => {
      const resData = response.data;
      if (resData.success) {
        setImageUrl(resData.data);
      }
    });
    setLoading(false);
  }, []);

  return (
    <div
      className="acc-setting"
      style={{
        position: "relative",
      }}
    >
      <h3>Imagen</h3>
      <StyledSetting>
        {imageUrl && (
          <img
            id="user-img-change"
            src={imageUrl}
            className="img img-responsive"
          />
        )}

        <div className="dropzoneContainer">
          <MyDropzone
            onDrop={handleOnDropImage}
            onDropRejected={handleDropReject}
          />
          {error && <FormErrorFeedback>{error}</FormErrorFeedback>}
        </div>
      </StyledSetting>
      <div className="save-stngs pd2">
        <ul>
          <li>
            <button
              type="button"
              className="btn-save-basic"
              onClick={handleSubmit}
            >
              Guardar
            </button>
          </li>
        </ul>
      </div>
      {loading && (
        <StyledSpinnerContainer>
          <Spinner></Spinner>
        </StyledSpinnerContainer>
      )}
    </div>
  );
};

// const mapStateToProps = (state) => ({

// })

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

export default connect(null, mapDispatchToProps)(ChangeImage);