All files / src/features/Merchants/GiveCreateMerchantPanel/hooks useAvatarUpload.ts

71.42% Statements 10/14
40% Branches 4/10
66.66% Functions 4/6
71.42% Lines 10/14

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49                3x 261x   261x 23x     261x                             261x       261x 23x 23x           261x            
import { useCallback, useEffect, useMemo } from "react";
import { useWatch } from "react-hook-form";
 
type Props = {
  fieldName: string;
  setValue: any;
};
 
export const useAvatarUpload = ({ setValue, fieldName }: Props) => {
  const thumbnailFile = useWatch({ name: fieldName });
 
  const previewUrl = useMemo(() => {
    return thumbnailFile ? URL.createObjectURL(thumbnailFile) : undefined;
  }, [thumbnailFile]);
 
  const handleChangeStatusV2 = useCallback(
    (file: File) => {
      if (file) {
        setValue(
          fieldName,
          Object.assign(file, {
            preview: URL.createObjectURL(file),
          }),
          { shouldDirty: true },
        );
      }
    },
    [setValue],
  );
 
  const handleDeleteImage = useCallback(() => {
    setValue(fieldName, null, { shouldValidate: true });
  }, [setValue]);
 
  useEffect(() => {
    return () => {
      Iif (thumbnailFile || previewUrl) {
        URL.revokeObjectURL(thumbnailFile.preview || previewUrl);
      }
    };
  }, [thumbnailFile, previewUrl]);
 
  return {
    handleDeleteImage,
    handleChangeImage: handleChangeStatusV2,
    previewUrl,
  };
};