import React, { useEffect, useState } from "react";

const DownloadFileLink = ({ data, filename, mimetype }) => {
  const [link, setLink] = useState("");
  const releaseLink = () => {
    if (link === "") return;
    URL.revokeObjectURL(link);
  };

  const makeFile = () => {
    const file = new Blob([data], { type: mimetype ?? "text/plain" });

    releaseLink();
    setLink(URL.createObjectURL(file));
  };

  useEffect(() => {
    if (!data) return;
    makeFile();
    return releaseLink;
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [data, filename, mimetype]);

  return (
    <a download={filename ?? "file.txt"} href={link}>
      {filename}
    </a>
  );
};

export default DownloadFileLink;
