Skip to content

Instantly share code, notes, and snippets.

@lebbe
Created September 5, 2023 16:03
Show Gist options
  • Save lebbe/83679f5ab9e8029fdac5df53ae9fb8b6 to your computer and use it in GitHub Desktop.
Save lebbe/83679f5ab9e8029fdac5df53ae9fb8b6 to your computer and use it in GitHub Desktop.

Revisions

  1. lebbe created this gist Sep 5, 2023.
    46 changes: 46 additions & 0 deletions useTxtBlobifier.tsx
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,46 @@
    /**
    * This hook returns an URL you can use in the href-attribute of an anchor element,
    * so the provided string will be downloaded as a txt-file.
    */
    function useTxtBlobifier(document: string) {
    const [loading, setLoading] = useState(true);
    const [url, setUrl] = useState('');

    // Remove the unused url instance if/when the document
    // changes, or when component unmounts.
    useEffect(() => {
    return () => {
    if (url) {
    URL.revokeObjectURL(url);
    }
    };
    }, [url]);

    const instance = { loading, url };

    useEffect(
    function () {
    if (document && typeof document === 'string') {
    // Fix typesetting issues if document is opened in the browser
    // (typically new tab, instead of downloading)
    const BOM = new Uint8Array([0xef, 0xbb, 0xbf]);

    const blob = new Blob([BOM, document], {
    type: 'text/plain',
    });

    setUrl(URL.createObjectURL(blob));
    setLoading(false);
    } else {
    setLoading(true);
    }
    },
    [document]
    );

    return { url, loading };
    }


    // TODO: I could release a component into npm that resembles react-pdf, only for txt-files instead.