UNPKG

react-async-csv-downloader

Version:

A small hook to enable asynchronous downloading of csv files

30 lines (29 loc) 817 B
import { useRef as s, useCallback as c } from "react"; const k = ({ asyncResolver: o, onStart: l, onSuccess: r, onError: i }) => { const a = s(null), d = c((n, t) => { const e = document.createElement("a"); document.body.appendChild(e), e.setAttribute("style", "display: none"), e.href = URL.createObjectURL(new Blob([n.file], { type: n.type })), e.download = t, e.click(), URL.revokeObjectURL(e.href), e.remove(); }, []), p = c( async (n) => { if (l?.(), o) { n.preventDefault(); try { const t = await o(); r?.(), d(t, a.current?.download); } catch (t) { i?.(t); } } }, [o, d, i, l, r] ); return { getProps: c(() => ({ linkRef: a, onClick: p }), [p]) }; }; export { k as useDownloadLink };