useDownload.ts 560 Bytes
import { useApi } from "util/useApi";
import { useCallback } from "react";

function downloadURL(url: string, name: string) {
  const link = document.createElement("a");
  link.setAttribute("download", name);
  link.href = url;
  link.click();
}

export function useDownload() {
  const api = useApi();
  const download = useCallback(
    async (id: number) => {
      const response = await api.get(`/items/${id}/`).json<any>();
      const { signed_url, name } = response.data;
      downloadURL(signed_url, name);
    },
    [api]
  );
  return download;
}