Commit 9c913283 authored by Omar Luna Hernández's avatar Omar Luna Hernández
Browse files

Se crea el custom hook encargado de la lógica de subir imágenes

parent f19edaa5
Loading
Loading
Loading
Loading
+72 −0
Original line number Diff line number Diff line
import { useState } from "react";
import { useDropzone } from "react-dropzone";
import { toast } from "react-toastify";
import { Image } from "../infraestructure/entities/image";
import { UseFormSetValue } from "react-hook-form";
import { PlaceFormValues } from "../infraestructure/entities/place";

export const useDropzoneMultiplesImages = (setValue: UseFormSetValue<PlaceFormValues>) => {
  const [imagesFiles, setImagesFiles] = useState<Image[]>([]);
  const [files, setFiles] = useState<File[]>([]);
  const MAX_SIZE = 10485760;
  const {getRootProps, getInputProps} = useDropzone(
    {
      maxSize: MAX_SIZE,
      accept: {
        'image/*': []
      },
      onDrop(acceptedFiles, fileRejections) {
        fileRejections.map(({file, errors}) => (
          toast.error("Error: " + errors[0].message +" : "+ file.name, {
            position: "bottom-right",
            autoClose: 1500,
            hideProgressBar: false,
            closeOnClick: true,
            pauseOnHover: false,
            draggable: true,
            progress: undefined,
            theme: "colored"
          })
        ));
        
        const backupImages = [...imagesFiles];
        const backupFiles = [...files];
        acceptedFiles.forEach((file, index)=>{
          if(imagesFiles.length<=10 && index<10){
            const preview = URL.createObjectURL(file);
            backupImages.push({file, preview});
            backupFiles.push(file);
          }else{
            toast.error("Error: Ha superado los 10 archivos", {
              position: "bottom-right",
              autoClose: 1500,
              hideProgressBar: false,
              closeOnClick: true,
              pauseOnHover: false,
              draggable: true,
              progress: undefined,
              theme: "colored"
            });
          }
        });
        setImagesFiles(backupImages);
        setFiles(backupFiles);
        console.log(backupFiles.length);
        setValue("imagesList", backupFiles, {shouldValidate:true});
      }
    }
  );

  const removeImage = (index: number) => {
    const backupImages = [...imagesFiles];
    const backupFiles = [...files];
    backupImages.splice(index, 1);
    backupFiles.splice(index, 1);
    setImagesFiles(backupImages);
    setFiles(backupFiles);
    setValue("imagesList", backupFiles, {shouldValidate:true});
    console.log(backupFiles.length);
  }

  return {getInputProps, getRootProps, imagesFiles, removeImage};
}
 No newline at end of file